如何编写Elasticsearch嵌套文档的多条件联合查询?
Elasticsearch多条件联合查询实现方案
逻辑拆解与核心思路
你的查询需求可拆解为三层逻辑:
- 两组必须同时满足的子条件组:
(field_id=1000 且 str_val包含"Jack")和(field_id=2000 且 int_val=30) - 额外跨索引过滤:基于
country索引中user1文档的country_ids字段过滤person索引数据
完整DSL查询示例
{ "query": { "bool": { "must": [ // 第一组子条件:field_id=1000 且 str_val包含"Jack" { "bool": { "must": [ {"term": {"field_id": 1000}}, {"match": {"str_val": "Jack"}} ] } }, // 第二组子条件:field_id=2000 且 int_val=30 { "bool": { "must": [ {"term": {"field_id": 2000}}, {"term": {"int_val": 30}} ] } } ], "filter": [ // 跨索引关联country的user1数据进行过滤 { "terms": { "country_id": { // 替换为person索引中对应国家ID的字段名 "index": "country", "id": "user1", "path": "country_ids" } } } ] } } }
关键细节调整说明
- 子条件组的嵌套
bool:用嵌套的bool.must保证每组内部两个条件同时成立,外层bool.must保证两组子条件同时满足,完全贴合你的逻辑关系。 - 跨索引过滤的实现:利用Elasticsearch
terms查询的内置跨索引引用能力,直接从country索引的user1文档中提取country_ids的值作为过滤条件,无需额外前置查询。 - 字段适配调整:
- 若
field_id是字符串类型,将值改为"1000"、"2000"格式 - 若
str_val需要精确包含前后通配,可替换为wildcard查询:{"wildcard": {"str_val": "*Jack*"}} - 确保
person索引中的国家ID字段名与示例中的country_id一致,不一致直接替换即可
- 若
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

