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

Elasticsearch如何通过update_by_query更新数组内的postedDate字段?

更新Elasticsearch数组中的嵌套字段

文档结构

你的目标文档结构如下:

"_source": {
    "dateCreated": "2023-07-12",
    "sources": [
      {
        "1": null,
        "lastUpdateDate": "2023-08-10T11:12:36.9848505",
        "postedDate": "2023-08-10T10:38:57.9440773" 
      }
    ]
}

已完成的更新操作

你已通过以下_update_by_query请求成功更新了dateCreated字段:

POST index/_update_by_query
{
  "script": {
    "source": "ctx._source.dateCreated='2023-07-12'",
    "lang": "painless"
  },
  "query": {
    "terms": {
      "_id": [
        "12345"
      ]
    }
  }
}

更新数组嵌套字段的方案

针对sources数组中的postedDate字段,可根据数组元素数量和更新需求选择不同的脚本写法:

场景1:数组仅含单个元素(如你的示例)

直接通过数组索引定位元素并修改:

POST index/_update_by_query
{
  "script": {
    "source": "ctx._source.sources[0].postedDate = '2023-08-10T12:00:00.0000000'",
    "lang": "painless"
  },
  "query": {
    "terms": {
      "_id": [
        "12345"
      ]
    }
  }
}

场景2:数组含多个元素,需批量更新所有元素的postedDate

通过循环遍历数组,统一修改每个元素的目标字段:

POST index/_update_by_query
{
  "script": {
    "source": """
      for (def item : ctx._source.sources) {
        item.postedDate = '2023-08-10T12:00:00.0000000';
      }
    """,
    "lang": "painless"
  },
  "query": {
    "terms": {
      "_id": [
        "12345"
      ]
    }
  }
}

场景3:数组含多个元素,仅更新符合条件的元素

在循环中添加判断逻辑,只修改满足特定条件的数组元素:

POST index/_update_by_query
{
  "script": {
    "source": """
      for (def item : ctx._source.sources) {
        // 示例:仅更新lastUpdateDate为2023-08-10的元素
        if (item.lastUpdateDate != null && item.lastUpdateDate.startsWith('2023-08-10')) {
          item.postedDate = '2023-08-10T12:00:00.0000000';
        }
      }
    """,
    "lang": "painless"
  },
  "query": {
    "terms": {
      "_id": [
        "12345"
      ]
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:42:34