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

查询带链式逻辑条件的Elasticsearch索引的最简方法

Elasticsearch 链式组合逻辑查询实现

核心实现靠bool查询嵌套即可:must对应逻辑AND,should对应逻辑OR,精确值匹配用term,数值区间比较用range,纯过滤场景优先把条件放filter子句,走缓存性能更好。


条件1:((type = "orange" and price > 10) or (type = "apple" and price > 8)) and on_sale=True

逻辑拆解:最外层为AND关系,必须同时满足「两组type+price组合的OR匹配」、「on_sale为true」两个要求。
对应最简DSL:

GET 你的商品索引名/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "must": [
                    {"term": {"type": "orange"}},
                    {"range": {"price": {"gt": 10}}}
                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {"term": {"type": "apple"}},
                    {"range": {"price": {"gt": 8}}}
                  ]
                }
              }
            ]
          }
        },
        {"term": {"on_sale": true}}
      ]
    }
  }
}

条件2:(type = "orange" or type = "apple") and (price <= 25 or on_sale=True)

逻辑拆解:最外层为AND关系,必须同时满足「type是orange/apple二选一」、「价格≤25/在售二选一」两个要求。
对应最简DSL:

GET 你的商品索引名/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {"term": {"type": "orange"}},
              {"term": {"type": "apple"}}
            ]
          }
        },
        {
          "bool": {
            "should": [
              {"range": {"price": {"lte": 25}}},
              {"term": {"on_sale": true}}
            ]
          }
        }
      ]
    }
  }
}

小提示:如果type字段是text类型需要分词匹配,把term换成match即可,数值、布尔类型字段直接用上面的写法就行。

内容的提问来源于stack exchange,提问作者question_man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:51:22