如何在Elasticsearch中仅返回_source的字段名而非字段值?
嘿,我之前刚好处理过类似的需求,Elasticsearch本身的_source参数只能控制字段的包含或排除,没法直接把字段值置为null,但我们可以借助**脚本字段(script_fields)**来实现你想要的效果,给你两种实用方案:
方案1:指定固定字段名
如果你已经明确知道需要保留哪些字段名,可以直接在脚本里构造对应的结构,把值设为null,同时关闭默认的_source返回:
{ "query": { "match_all": {} }, "script_fields": { "_source": { "script": { "source": """ def result = new HashMap(); // 这里替换成你需要的字段名 result.put('name', null); result.put('types', null); return result; """ } } }, "_source": false }
执行这个查询后,返回的hits部分就会是你期望的格式:
[ {"_source": {"name": null}}, {"_source": {"types": null}} ]
方案2:动态遍历所有字段
如果你的文档字段不固定,想要保留_source里所有字段的名称但都设为null,可以用脚本遍历原始_source的字段键,自动生成结构:
{ "query": { "match_all": {} }, "script_fields": { "_source": { "script": { "source": """ def result = new HashMap(); // 遍历原始_source的所有字段,将值设为null for (entry in params._source.entrySet()) { result.put(entry.getKey(), null); } return result; """, "params": { "_source": "_source" } } } }, "_source": false }
这个方案会自动适配不同文档的字段结构,不用手动维护字段列表。
需要注意的是,脚本字段的性能取决于你的数据量,如果是大规模查询,建议先在小数据集上测试效果,避免性能瓶颈。
内容的提问来源于stack exchange,提问作者Andrei Galatyn
相关产品推荐
相关产品推荐

