如何编写基于文档属性的ElasticSearch条件should子句查询
基于文档属性动态指定should子句的Elasticsearch查询实现
根据需求,我们需要返回两类符合条件的文档:
- 颜色为
red且匹配原有承运商ID列表的文档 - 颜色不为
red且匹配另一组承运商ID列表的文档
可以通过在bool查询中嵌套多条件分支来实现,修改后的查询如下:
{ "query": { "bool": { "must": [ { "match_phrase": { "product_status": { "query": "active" } } }, { "bool": { "should": [ // 第一类:红色文档 + 原有承运商ID列表 { "bool": { "must": [ { "term": { "color": "red" } }, { "terms": { "shipper_id": ["39", "40", "41", "48", "49", "50"] } } ] } }, // 第二类:非红色文档 + 新承运商ID列表 { "bool": { "must": [ { "bool": { "must_not": [ { "term": { "color": "red" } } ] } }, { "terms": { "shipper_id": ["101", "102", "103"] // 替换为你的另一组ID } } ] } } ], "minimum_should_match": 1 // 确保至少匹配其中一个分支 } } ], "filter": [], "should": [], "must_not": [] } }, "sort": [ { "last_modified": "DESC" } ], "from": 0, "size": 50 }
关键说明:
- 外层
must保留了product_status: active的全局条件,确保所有返回文档都是激活状态 - 新增的嵌套
bool should包含两个分支,分别对应两种业务场景 - 每个分支内部用
bool must实现逻辑与:必须同时满足颜色条件和承运商ID匹配 - 添加
minimum_should_match: 1确保文档至少匹配两个分支中的一个,避免无结果返回 - 用
terms替代多个term查询,让语法更简洁高效
内容的提问来源于stack exchange,提问作者billrichards
相关产品推荐
相关产品推荐

