Elasticsearch查询如何仅返回单个存在的字段而非字段列表
实现方案
你可以通过两种常用方式完成需求,两种方案都会动态生成单个统一的出生相关字段,无需修改原有索引结构,也不用改动你的过滤逻辑。
方案1:使用运行时字段(Runtime Field,ES 7.11及以上版本推荐)
在查询中新增运行时字段,按自定义优先级取两个字段中存在的返回,最终只返回这一个动态字段即可,完整修改后的查询语句如下:
{ "runtime_mappings": { "birthValue": { "type": "keyword", "script": """ if(doc.containsKey('fullBirthDate') && !doc['fullBirthDate'].empty) { return doc['fullBirthDate'].value; } return doc['yearOfBirth'].value; """ } }, "_source": false, "fields": ["birthValue"], "size": 1000, "query": { "bool": { "filter": { "bool": { "must": [ { "bool": { "should": [ { "range": { "yearOfBirth": { "gte": "1900", "lte": "2020" } } }, { "range": { "fullBirthDate": { "gte": "1900", "lte": "2020" } } } ], "minimum_should_match": 1 } } ] } } } } }
说明:
- 你可以自行调整脚本里的优先级,想要优先返回
yearOfBirth就把两个判断顺序反过来即可 _source设为false可以避免返回原始的两个字段,减少返回数据体积- 字段类型可以根据你的实际需求调整为
date或者其他类型
方案2:使用脚本字段(Script Fields,兼容低版本ES)
如果你使用的ES版本低于7.11,可以用脚本字段实现:
{ "_source": false, "script_fields": { "birthValue": { "script": { "lang": "painless", "source": """ if(params._source.containsKey('fullBirthDate')) { return params._source['fullBirthDate']; } return params._source['yearOfBirth']; """ } } }, "size": 1000, "query": { "bool": { "filter": { "bool": { "must": [ { "bool": { "should": [ { "range": { "yearOfBirth": { "gte": "1900", "lte": "2020" } } }, { "range": { "fullBirthDate": { "gte": "1900", "lte": "2020" } } } ], "minimum_should_match": 1 } } ] } } } } }
内容的提问来源于stack exchange,提问作者megablochesk
相关产品推荐
相关产品推荐

