索引结构设计
- 商品名称:使用
text
类型,并配置合适的分析器,如 ik_max_word
(针对中文),以支持分词搜索。例如:
{
"mappings": {
"properties": {
"product_name": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
- 商品描述:同样使用
text
类型和合适分析器,以支持更详细的文本搜索。
{
"mappings": {
"properties": {
"product_description": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
- 价格:使用
float
或 integer
类型(根据价格精度),用于范围查询和排序。
{
"mappings": {
"properties": {
"price": {
"type": "float"
}
}
}
}
- 销量:使用
integer
类型,用于范围查询和排序。
{
"mappings": {
"properties": {
"sales": {
"type": "integer"
}
}
}
}
- 品牌:使用
keyword
类型,用于精确匹配。
{
"mappings": {
"properties": {
"brand": {
"type": "keyword"
}
}
}
}
查询语句构建
- 多条件查询:使用
bool
查询来组合不同条件。例如,查询商品名称包含 "手机",价格在 1000 到 5000 之间,品牌为 "华为" 的商品:
{
"query": {
"bool": {
"must": [
{
"match": {
"product_name": "手机"
}
},
{
"range": {
"price": {
"gte": 1000,
"lte": 5000
}
}
},
{
"term": {
"brand": "华为"
}
}
]
}
}
}
- 模糊查询:如果需要对商品描述进行模糊搜索,可以使用
fuzzy
查询。例如,模糊查询描述中包含 "智能" 的商品:
{
"query": {
"fuzzy": {
"product_description": {
"value": "智能",
"fuzziness": "AUTO"
}
}
}
}
排序策略实现思路
- 相关性排序:默认情况下,ElasticSearch 会根据文档与查询条件的相关性进行排序。可以通过调整
match
查询中的 boost
参数来调整某些字段在相关性计算中的权重。例如,提高商品名称在相关性中的权重:
{
"query": {
"bool": {
"must": [
{
"match": {
"product_name": {
"query": "手机",
"boost": 2
}
}
},
{
"match": {
"product_description": "手机"
}
}
]
}
}
}
- 销量排序:使用
sort
参数,按照销量降序排列:
{
"query": {
"match_all": {}
},
"sort": [
{
"sales": {
"order": "desc"
}
}
]
}
- 价格排序:同样使用
sort
参数,按照价格升序排列:
{
"query": {
"match_all": {}
},
"sort": [
{
"price": {
"order": "asc"
}
}
]
}
- 多维度排序:可以组合多个排序字段,例如先按销量降序,再按价格升序:
{
"query": {
"match_all": {}
},
"sort": [
{
"sales": {
"order": "desc"
}
},
{
"price": {
"order": "asc"
}
}
]
}