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
相关产品推荐
相关产品推荐

