You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:15:54