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

如何在Elasticsearch查询结果顶层添加自定义参数?

在Elasticsearch查询结果顶层添加指定字段

要将_source中的timestamp字段提取到查询结果的顶层,可通过以下方式实现:

方法1:使用script_fields生成关联字段

通过script_fields参数可以在结果中新增关联字段,取值指向_source中的对应字段。

示例查询(字段已索引)

如果timestamp字段已被索引,可直接通过doc取值:

GET /testing/_doc/bwDimoUBulk-8kIUdLcv
{
  "script_fields": {
    "timestamp": {
      "script": "doc['timestamp'].value"
    }
  },
  "_source": true
}

示例查询(字段未索引)

若timestamp未被索引,直接从_source中读取:

GET /testing/_doc/bwDimoUBulk-8kIUdLcv
{
  "script_fields": {
    "timestamp": {
      "script": "_source.timestamp"
    }
  },
  "_source": true
}

返回结果说明

执行后,timestamp会出现在fields对象下:

{
  "_index": "testing",
  "_type": "reading",
  "_id": "bwDimoUBulk-8kIUdLcv",
  "_version": 2,
  "_seq_no": 7468,
  "_primary_term": 15,
  "found": true,
  "_source": {
    "device": {
      "id": 1435
    },
    "service": 3,
    "value": 0,
    "timestamp": 1723672453,
    "created": "2024-08-15T07:54:13+10:00",
    "updated": "2023-01-10T18:57:28+10:00"
  },
  "fields": {
    "timestamp": [1723672453]
  }
}

方法2:客户端处理实现完全匹配结构

如果需要timestamp直接作为顶层字段(而非嵌套在fields中),原生Elasticsearch查询无法直接生成该结构,建议在客户端获取结果后,将fields.timestamp[0]提取到顶层对象中,即可得到你期望的格式。


内容的提问来源于stack exchange,提问作者user3818576

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:42:30