Elasticsearch DSL如何筛选type为opportunity且locations数组内id在指定列表的文档
Elasticsearch 嵌套数组条件查询实现方案
前提说明
你需要先确认索引中locations字段的映射类型:
- 如果是
nested类型(推荐用于数组对象,避免字段扁平化匹配错误),使用第一种方案 - 如果是普通
object类型,使用第二种简化方案
方案1:locations为nested类型(推荐)
你需要用nested查询包裹内部数组对象的匹配规则,完整代码如下:
# 你要匹配的location.id目标列表,注意示例中location.id为字符串类型,需保持类型一致 target_location_ids = ["1", "2", "3"] # 组合查询条件 combined_query = ElasticQ( 'bool', must=[ # 条件1:type固定为opportunity ElasticQ('match', type='opportunity'), # 条件2:locations数组中存在id在目标列表中的对象 ElasticQ( 'nested', path='locations', query=ElasticQ('terms', **{'locations.id': target_location_ids}) ) ] ) query = self.index.search().query(combined_query)
方案2:locations为普通object类型
如果没有设置nested类型,可以省略nested包裹,直接查询:
target_location_ids = ["1", "2", "3"] combined_query = ElasticQ( 'bool', must=[ ElasticQ('match', type='opportunity'), ElasticQ('terms', **{'locations.id': target_location_ids}) ] ) query = self.index.search().query(combined_query)
注意事项
- 你提供的示例数据中
locations.id为字符串类型,目标ID列表如果是数字格式需要先转为字符串,否则terms查询无法匹配到结果 - 如果后续需要同时匹配同一个location对象的多个属性(比如同时要求id为555且type为CI),必须使用nested类型+方案1的写法,普通object类型会将数组所有对象的字段值打平,会出现跨对象匹配的错误
内容的提问来源于stack exchange,提问作者Christinerex
相关产品推荐
相关产品推荐

