如何在ElasticSearch中根据查询条件获取匹配文档的全部字段名?
实现方案
你可以通过Painless脚本动态提取文档中实际存在的嵌套字段路径,完全匹配你的需求,具体操作如下:
方案:查询时通过Script Field动态生成字段列表
直接在查询DSL中嵌入脚本,从文档原始_source中遍历嵌套对象的键,拼接为你需要的完整字段路径:
GET /test-product/_search { "query": { "term": { "user.keyword": "1" // 替换为你要查询的user值,user如果是keyword类型可去掉.keyword后缀 } }, "script_fields": { "existing_field_paths": { "script": { "lang": "painless", "source": """ def result = []; // 遍历profile下的所有实际存在的字段 if (params._source.containsKey('profile')) { def profile = params._source.profile; for (def k : profile.keySet()) { result.add('profile.' + k); } } // 遍历product下的所有实际存在的字段 if (params._source.containsKey('product')) { def product = params._source.product; for (def k : product.keySet()) { result.add('product.' + k); } } return result; """ } } }, "_source": false // 关闭原始文档返回,只返回生成的字段路径列表 }
效果验证
- 查询
user: "1"时,返回的existing_field_paths值为:["profile.name","profile.age","profile.height","product.price","product.name","product.weight"] - 查询
user: "2"时,返回的existing_field_paths值为:["profile.name","profile.age","product.name"]
性能优化建议
如果该查询是高频场景,你可以在写入文档时预先计算好所有存在的字段路径,存入一个单独的数组类型字段(比如field_list),查询时直接返回该字段即可,不需要每次查询执行脚本,性能更高。
内容的提问来源于stack exchange,提问作者Aaron Jin
相关产品推荐
相关产品推荐

