如何仅通过Elasticsearch返回_source内文档内容,去除外层_source键?
问题描述
需要从Elasticsearch检索10000条文档,希望直接获取_source内的字段内容,不要保留外层的_source键。当前使用的查询语句如下:
GET geojson_entities/_search?filter_path=hits.hits._source { "size": 10000, "_source": { "includes": [ "type" ] } }
当前返回的hits.hits数组结构:
[ { "_source": { "type": "Feature" } }, ... ]
期望的hits.hits数组格式:
[ { "type": "Feature" }, ... ]
目前可以通过JavaScript代码处理:
const results = response.map(res => res._source)
想了解是否仅通过Elasticsearch就能实现该格式要求?
解决方案
可以通过修改filter_path参数的写法实现,不需要客户端额外处理。将原请求的filter_path从hits.hits._source改为hits.hits._source.*,具体查询语句如下:
GET geojson_entities/_search?filter_path=hits.hits._source.* { "size": 10000, "_source": { "includes": [ "type" ] } }
这样Elasticsearch会将每个文档_source下的字段直接提升到hit对象的顶层,返回的hits.hits数组结构就会符合你的期望。如果_source包含大量字段,这种方法依然有效,通配符*会匹配_source下的所有字段,无需逐个指定。
内容的提问来源于stack exchange,提问作者Habtamu
相关产品推荐
相关产品推荐

