如何编写Elasticsearch 8.5的复合AND-OR查询DSL语句?
Elasticsearch 8.5 DSL 实现方案
直接用布尔查询(bool)的should子句实现你的OR逻辑,每个括号内的AND逻辑用must子句组合,具体DSL如下:
{ "query": { "bool": { "should": [ // 第一个条件:attr1 IS NOT NULL AND attr2 IS NULL { "bool": { "must": [ {"exists": {"field": "attr1"}}, {"bool": {"must_not": {"exists": {"field": "attr2"}}}} ] } }, // 第二个条件:attr3 IS NOT NULL AND attr4 IS NULL { "bool": { "must": [ {"exists": {"field": "attr3"}}, {"bool": {"must_not": {"exists": {"field": "attr4"}}}} ] } }, // 第三个条件:attr5 = true { "term": {"attr5": true} } ], "minimum_should_match": 1 } } }
关键说明:
exists查询对应SQL的IS NOT NULL,用来判断字段存在且不为空bool.must_not + exists对应SQL的IS NULL,用来判断字段不存在或为空- 内层
bool.must用来组合AND条件,确保两个子条件同时满足 - 外层
bool.should实现OR逻辑,minimum_should_match: 1保证至少满足一个条件,避免无匹配结果 term查询用于精确匹配布尔值true,适合布尔类型字段
如果之前用评分方式结果不稳定,是因为评分查询会根据匹配度计算分数,若不需要评分,可将整个查询放到bool.filter中,这样不会计算评分,性能更稳定:
{ "query": { "bool": { "filter": [ { "bool": { "should": [ {"bool": {"must": [{"exists": {"field": "attr1"}}, {"bool": {"must_not": {"exists": {"field": "attr2"}}}}]}}, {"bool": {"must": [{"exists": {"field": "attr3"}}, {"bool": {"must_not": {"exists": {"field": "attr4"}}}}]}}, {"term": {"attr5": true}} ], "minimum_should_match": 1 } } ] } } }
内容的提问来源于stack exchange,提问作者Carlos
相关产品推荐
相关产品推荐

