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

Elasticsearch:如何在must中结合Filter与Bool实现AND条件?

如何让Elasticsearch查询中的wildcard条件与filter语句形成AND关系?

我尝试在must中结合filter与bool/should,以下查询由应用自动生成(因此存在嵌套结构),需要调整查询使wildcard条件与filter语句形成AND关系:

"query":{
   "bool":{
      "filter": {
         "bool": {
           "must": [],
           "must_not": [],
           "should": [],
           "filter": {
             "bool": {
               "should": [
                 {
                   "wildcard": {
                     "attachment.content_type.keyword": "video/*"
                   }
                 }
               ],
               "must": [],
               "must_not": [],
               "filter": [
                 {
                   "terms": {
                     "status.keyword": [
                       "xxx"
                     ]
                   }
                 }
               ]
             }
           }
         }
       }
   }
}

调整后的查询

要实现两个条件的AND关系,只需将wildcard条件和原filter中的terms条件放到同一个bool.filter数组中即可。bool查询的filter、must字段内的多个条件默认都是逻辑与(AND)关系,同时可以简化不必要的嵌套结构:

"query":{
   "bool":{
      "filter": [
        {
          "wildcard": {
            "attachment.content_type.keyword": "video/*"
          }
        },
        {
          "terms": {
            "status.keyword": [
              "xxx"
            ]
          }
        }
      ]
   }
}

说明

原查询的嵌套结构过于冗余,且should子句在未设置minimum_should_match: 1的情况下,如果所在bool没有其他must/filter条件,会被视为可选匹配。通过将两个需要同时满足的条件直接放入最外层bool.filter数组,既简化了结构,又确保了两个条件必须同时匹配(AND关系)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:34:57