如何编写Elastic Search查询匹配空日期与布尔字段?
针对不同字段类型的Elasticsearch空值查询方案
你的现有查询仅适用于字符串类型字段的空字符串("")场景,但日期、布尔类型的空值逻辑和存储方式不同,以下是对应解决方案:
1. 字符串字段(优化版)
你的原有查询可以简化,exists + term: "" 可直接用更简洁的写法,若需严格匹配空字符串,原逻辑也成立:
GET _search { "size": 2, "query": { "bool": { "must": [ {"match": {"product": "device"}}, {"range": {"time": {"from": "2022-06-01T05:00:00.000Z", "to": "2022-09-15T23:59:59.999Z"}}} ], "filter": [ {"term": {"device_id": ""}} ] } } }
注:如果字段是text类型,建议用match: {"device_id": ""},term更适配keyword类型字段
2. 日期类型字段的空值查询
日期字段的"空值"通常分两种场景,按需选择查询方式:
场景A:字段存在但值为null
若字段映射允许存储null,直接用term查询null值:
GET _search { "size": 2, "query": { "bool": { "must": [ {"match": {"product": "device"}}, {"range": {"time": {"from": "2022-06-01T05:00:00.000Z", "to": "2022-09-15T23:59:59.999Z"}}} ], "filter": [ {"term": {"your_date_field": null}} ] } } }
场景B:字段不存在或值为null
用bool的must_not + exists组合查询:
GET _search { "size": 2, "query": { "bool": { "must": [ {"match": {"product": "device"}}, {"range": {"time": {"from": "2022-06-01T05:00:00.000Z", "to": "2022-09-15T23:59:59.999Z"}}} ], "filter": [ {"bool": {"must_not": {"exists": {"field": "your_date_field"}}}} ] } } }
3. 布尔类型字段的空值查询
布尔字段的空值同样分两种场景:
场景A:字段存在但值为null
直接用term查询null值:
GET _search { "size": 2, "query": { "bool": { "must": [ {"match": {"product": "device"}}, {"range": {"time": {"from": "2022-06-01T05:00:00.000Z", "to": "2022-09-15T23:59:59.999Z"}}} ], "filter": [ {"term": {"your_boolean_field": null}} ] } } }
场景B:字段不存在或值为null
使用must_not + exists组合查询:
GET _search { "size": 2, "query": { "bool": { "must": [ {"match": {"product": "device"}}, {"range": {"time": {"from": "2022-06-01T05:00:00.000Z", "to": "2022-09-15T23:59:59.999Z"}}} ], "filter": [ {"bool": {"must_not": {"exists": {"field": "your_boolean_field"}}}} ] } } }
注意:如果布尔字段映射中设置了null_value(比如null_value: false),需对应查询null_value指定的值,即term: {"your_boolean_field": false}
内容的提问来源于stack exchange,提问作者Hermione
相关产品推荐
相关产品推荐

