Elasticsearch如何实现字段值匹配或字段不存在的条件查询
Elasticsearch 查询实现方案
你需要的「audience.gender = 'Male' 或者 audience.gender 不存在」逻辑可以通过 bool 组合查询实现,具体分两种场景:
场景1:audience 为普通 object 类型(默认 mapping 配置)
如果创建索引时没有特意设置 audience 为 nested 类型,默认属于普通 object 类型,使用以下DSL即可:
GET /你的索引名/_search { "query": { "bool": { "should": [ // 条件1:audience.gender 为 Male { "term": { "audience.gender.keyword": "Male" } }, // 条件2:audience.gender 不存在 { "bool": { "must_not": [ { "exists": { "field": "audience.gender" } } ] } } ], // 强制至少满足1个should条件 "minimum_should_match": 1 } } }
场景2:audience 为 nested 类型
如果你的 mapping 中 audience 被定义为 nested 类型,需要套 nested 查询:
GET /你的索引名/_search { "query": { "bool": { "should": [ { "nested": { "path": "audience", "query": { "term": { "audience.gender.keyword": "Male" } } } }, { "bool": { "must_not": [ { "nested": { "path": "audience", "query": { "exists": { "field": "audience.gender" } } } } ] } } ], "minimum_should_match": 1 } } }
注意事项
- 可以执行
GET /你的索引名/_mapping查看 audience 字段的具体类型,选择对应查询方案 - 如果 gender 字段本身被定义为 keyword 类型,无需加
.keyword后缀,直接写audience.gender即可
内容的提问来源于stack exchange,提问作者fempyrean
相关产品推荐
相关产品推荐

