You need to enable JavaScript to run this app. 如何实现带if-else分支逻辑的Elasticsearch多条件联合查询
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带if-else分支逻辑的Elasticsearch多条件联合查询

多条件分支Elasticsearch查询实现

你需要的if-else分支逻辑可以通过ES原生的bool组合查询实现,整体逻辑用should包裹两个互斥的条件分支,过滤规则统一放在filter上下文中,不参与相关性算分,查询性能更优。

完整查询语句

{
  "query": {
    "bool": {
      "should": [
        // 分支1:isQualified = true的过滤规则
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "isQualified": true
                }
              },
              {
                "term": {
                  "stud_ext_curr_status": "C-ve"
                }
              }
            ]
          }
        },
        // 分支2:isQualified = false的过滤规则
        {
          "bool": {
            "filter": [
              {
                "term": {
                  "isQualified": false
                }
              },
              {
                "exists": {
                  "field": "pending_subjects"
                }
              },
              {
                "bool": {
                  "should": [
                    // 子规则1:pending_subjects不含SCIENCE直接命中
                    {
                      "bool": {
                        "must_not": [
                          {
                            "term": {
                              "pending_subjects": "SCIENCE"
                            }
                          }
                        ]
                      }
                    },
                    // 子规则2:pending_subjects含SCIENCE需要同时满足status为A+ve
                    {
                      "bool": {
                        "must": [
                          {
                            "term": {
                              "pending_subjects": "SCIENCE"
                            }
                          },
                          {
                            "term": {
                              "stud_ext_curr_status": "A+ve"
                            }
                          }
                        ]
                      }
                    }
                  ],
                  "minimum_should_match": 1
                }
              }
            ]
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

注意事项

如果你的stud_ext_curr_status、pending_subjects字段映射为text类型,查询时需要在字段名后追加.keyword后缀(例如pending_subjects.keyword),避免分词导致匹配结果不符合预期。

按照你提供的样例文档,该查询最终会命中3条记录:文档3、ID为1111的未合格文档、文档4,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 17:15:03