Elasticsearch如何筛选含null值gyldigTil的livsforloeb的Vrvirksomhed
筛选包含至少一个gyldigTil为null的livsforloeb的Vrvirksomhed数据
问题原因
你之前使用的must_not + exists查询是针对整个文档的字段存在性判断,但livsforloeb属于数组/嵌套对象结构:当数组里部分元素的gyldigTil有值、部分为null时,整个文档的livsforloeb.periode.gyldigTil字段会被判定为“存在”,导致这类符合条件的文档被错误排除。
解决方案
要实现“任意一个livsforloeb的gyldigTil为null即匹配”,必须使用nested查询(前提是livsforloeb字段的映射类型为nested,普通object类型会扁平化存储,无法实现精准的嵌套元素查询)。
步骤1:确保字段映射为nested类型
如果你的索引还未将livsforloeb设置为nested类型,需先更新映射(示例):
PUT /your_index_name/_mapping { "properties": { "livsforloeb": { "type": "nested", "properties": { "periode": { "properties": { "gyldigTil": { "type": "date" // 根据实际字段类型调整,比如keyword } } } } } } }
步骤2:编写nested查询
以下两种写法均可实现需求:
写法1:用exists判断字段不存在/为null
GET /your_index_name/_search { "query": { "nested": { "path": "livsforloeb", "query": { "bool": { "must_not": [ { "exists": { "field": "livsforloeb.periode.gyldigTil" } } ] } }, "inner_hits": {} // 可选,返回匹配的具体livsforloeb元素 } } }
写法2:直接匹配null值
如果字段允许存储null,也可以用term查询直接匹配:
GET /your_index_name/_search { "query": { "nested": { "path": "livsforloeb", "query": { "term": { "livsforloeb.periode.gyldigTil": null } } } } }
原理说明
nested查询会逐个遍历每个livsforloeb对象,在独立的上下文里检查条件——只要有一个对象满足gyldigTil为null,整个Vrvirksomhed文档就会被命中,完美解决了多元素数组的部分匹配问题。
内容的提问来源于stack exchange,提问作者Christian Schmidt
相关产品推荐
相关产品推荐

