You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:22:55