如何让Elasticsearch查询仅返回原始数据,去除_source等包装?
让Elasticsearch查询返回纯原始数据数组的方案
Elasticsearch原生_search API的响应结构固定包含hits等元数据,无法直接返回纯原始数据数组,但可以通过以下两种方式满足你的需求(成功时返回纯数组,错误时保留元数据):
一、客户端侧处理(最简单通用)
这种方式无需修改服务端配置,所有处理在客户端完成:
- 执行查询时,添加
filter_path=hits.hits._source参数过滤冗余元数据,示例请求:
此时响应会简化为:GET /your_index/_search?filter_path=hits.hits._source { "query": { "match_all": {} } }{ "hits": { "hits": [ { "_source": { "field1": "val1", "field2": "val2" } }, { "_source": { "field1": "val3", "field2": "val4" } } ] } } - 在客户端代码中提取
_source字段组成数组,比如JavaScript中:const rawDataArray = response.hits.hits.map(item => item._source); - 错误处理:如果请求出错(如语法错误、索引不存在),Elasticsearch会直接返回包含
error和status的元数据响应,客户端可直接捕获处理,不会进入正常结果提取流程。
二、服务端侧通过Search Request Pipeline处理(适合需要服务端直接返回的场景)
如果必须让服务端直接返回纯数组,可使用Elasticsearch 7.10+支持的Search Request Pipeline,在响应返回前重组结构:
- 创建一个用于提取原始数据的pipeline:
PUT _ingest/pipeline/extract_raw_source { "processors": [ { "script": { "source": """ ctx.response = ctx.response.hits.hits.stream().map(hit -> hit._source).collect(Collectors.toList()); """ } } ] } - 查询时指定该pipeline,示例请求:
成功时会直接返回纯原始数据数组:GET /your_index/_search?pipeline=extract_raw_source { "query": { "match_all": {} } }[ { "field1": "val1", "field2": "val2" }, { "field1": "val3", "field2": "val4" } ] - 错误处理:当查询出错时,Elasticsearch会跳过pipeline处理,直接返回包含
error、status的标准错误元数据,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Midiman
相关产品推荐
相关产品推荐

