使用Elasticsearch的update by query API,配合nested查询,可以实现批量更新嵌套字段。代码示例如下:
POST my_index/_update_by_query
{
"query": {
"nested": {
"path": "my_nested_field",
"query": {
"bool": {
"must": [
{"match": {"my_nested_field.name": "foo"}},
{"match": {"my_nested_field.interests": "basketball"}}
]
}
}
}
},
"script": {
"source": " ctx._source.my_nested_field.interests = params.new_interests ",
"lang": "painless",
"params": {
"new_interests": ["football", "hiking"]
}
}
}
其中,"query"中的nested查询指定了需要更新的嵌套文档的条件;"script"中的source代码段定义了如何更新嵌套字段的内容。需要注意的是,painless脚本通常只适用于小规模数据的更新,对于大规模数据,需要考虑使用批量更新的方式来优化性能。