在电商平台的商品筛选系统中,我们常常遇到这样的困境:用户希望同时按照价格区间、品牌、用户评价等多维度筛选商品,但简单的查询组合要么返回结果太少,要么出现大量无关商品。这背后其实是一个典型的布尔逻辑组合问题——而这正是Elasticsearch的bool查询大显身手的场景。
某跨境电商平台需要实现这样的商品筛选逻辑:
用bool查询可以完美表达这种复杂逻辑:
json复制{
"query": {
"bool": {
"must": [
{ "term": { "category": "electronics" }},
{ "range": { "price": { "gte": 2000, "lte": 5000 }}}
],
"should": [
{ "range": { "rating": { "gte": 90 }}},
{ "range": { "sales": { "gt": 1000 }}}
],
"minimum_should_match": 1,
"must_not": [
{ "term": { "condition": "used" }}
]
}
}
}
性能优化要点:
filter用于不参与评分的条件(如库存状态)must_not比must消耗更多资源,必要时改用filter+范围查询should子句数量,避免评分计算过载实际测试显示,合理使用bool查询可以使复杂筛选的响应时间从1200ms降至300ms左右。
新闻聚合平台遇到这样的问题:当搜索"区块链技术"时,同时匹配标题和正文的文章,评分反而不如只匹配标题的文章高。这是因为默认的评分策略会平均各字段的匹配程度。
dis_max查询可以确保以最佳匹配字段的评分为主:
json复制{
"query": {
"dis_max": {
"queries": [
{ "match": { "title": "区块链技术" }},
{ "match": { "content": "区块链技术" }}
],
"tie_breaker": 0.3
}
}
}
参数配置建议:
tie_breaker取值0.1-0.4效果最佳json复制{ "match": { "title": { "query": "区块链技术", "boost": 2 }}}
某科技媒体采用此方案后,相关文章点击率提升了40%。
视频平台需要将热门内容与搜索关键词结合排序。单纯按热度或相关度排序都不理想,function_score提供了完美的折中方案:
json复制{
"query": {
"function_score": {
"query": { "match": { "title": "科幻电影" }},
"functions": [
{
"field_value_factor": {
"field": "view_count",
"modifier": "log1p",
"factor": 0.1
}
},
{
"gauss": {
"publish_date": {
"origin": "now",
"scale": "30d",
"offset": "15d",
"decay": 0.5
}
}
}
],
"boost_mode": "sum",
"score_mode": "sum"
}
}
}
这个查询实现了:
实用技巧:
modifier使用log1p避免大数值主导score_mode选择企业文档系统需要实现复杂的权限过滤:
json复制{
"query": {
"bool": {
"filter": [
{
"bool": {
"should": [
{ "terms": { "department": ["技术部","公共事务部"] }},
{ "term": { "is_public": true }}
],
"must_not": [
{ "terms": { "doc_id": [123,456] }}
]
}
}
]
}
}
}
性能关键:
酒店搜索需要同时考虑:
json复制{
"query": {
"bool": {
"must": {
"geo_distance": {
"distance": "3km",
"location": "40.7128,-74.0060"
}
},
"filter": [
{ "range": { "price": { "gte": 300, "lte": 800 }}}
],
"should": [
{ "range": { "rating": { "gte": 4, "boost": 2 }}}
]
}
}
}
实施建议:
某旅游平台采用这种分层查询策略后,酒店预订转化率提升了25%。