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

如何在Elasticsearch DSL查询中添加指定ID的排除检索条件

要实现排除id为3、4、5的文档,仅保留id为6且Country Owner.id.keyword/Territory Owner.id.keyword值为ABC101的结果,只需在原有的bool查询结构中新增must_not排除子句即可,修改后的完整代码如下:

a = {'from': 0, 'size': 200,'query': {
    'bool': {
      'should': [                              
        {
          'terms': {
            'Country Owner.id.keyword': [
              'ABC101'
            ]
          }
        },
        {
          'terms': {
            'Territory Owner.id.keyword': [
              'ABC101'
            ]
          }
        }
      ],
      # 新增排除条件,过滤id为3、4、5的文档
      'must_not': [
        {
          'terms': {
            'id': [3,4,5]
          }
        }
      ],
      # 确保返回结果至少匹配一个值为ABC101的字段条件
      'minimum_should_match': 1
    }
  }
}

修改说明:

  • 新增must_not子句:Elasticsearch查询时会自动过滤掉所有id字段值为3、4、5的文档,满足排除要求
  • 新增minimum_should_match: 1配置:保证返回的文档必须至少匹配Country Owner.id.keyword或Territory Owner.id.keyword其中一个的值为ABC101的条件,避免无must子句时bool查询返回所有未被排除的无关文档

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:45:04