Elasticsearch带OR/AND组合逻辑的nested query编写方法咨询
Elasticsearch 查询语句编写说明
首先明确字段类型场景,两种场景对应不同写法:
- 若
name和country为文档顶级非嵌套字段,无需使用nested query,直接用bool查询组合条件即可 - 若
name和country隶属于某个nested类型的对象字段,才需要使用nested query语法
场景1:顶级字段查询(无嵌套)
通过bool.should包裹两组bool.must条件,每组对应一组需要同时满足的配对规则:
GET /你的索引名/_search { "query": { "bool": { "should": [ { "bool": { "must": [ { "term": { "name": "John" } }, { "term": { "country": "US" } } ] } }, { "bool": { "must": [ { "term": { "name": "Andy" } }, { "term": { "country": "UK" } } ] } } ], "minimum_should_match": 1 } } }
注:如果你的
name和country字段是text类型,需要把term查询替换为match查询。
场景2:字段属于nested类型对象(假设嵌套字段名为user)
如果你的文档实际结构如下(即name和country存放在nested类型的user字段下):
{ "user": [ { "name": "...", "country": "..." } ] }
对应的nested query写法如下:
GET /你的索引名/_search { "query": { "bool": { "should": [ { "nested": { "path": "user", "query": { "bool": { "must": [ { "term": { "user.name": "John" } }, { "term": { "user.country": "US" } } ] } } } }, { "nested": { "path": "user", "query": { "bool": { "must": [ { "term": { "user.name": "Andy" } }, { "term": { "user.country": "UK" } } ] } } } } ], "minimum_should_match": 1 } } }
注:需要把语句中的
user替换为你实际的嵌套字段路径,字段名和索引名也需要和实际业务配置保持一致。
内容的提问来源于stack exchange,提问作者user1187968
相关产品推荐
相关产品推荐

