如何在Elasticsearch中使用Update API更新数据集及新增字段
Got it, let's break down your two questions about Elasticsearch's Update API step by step with practical examples you can use right away.
The Update API gives you flexible ways to update documents. Here are the most common approaches:
Update a single document by ID
If you know the exact document ID, use the_updateendpoint with thedocparameter to overwrite or update existing fields:POST /your_index_name/_update/your_document_id { "doc": { "existing_field": "new_value" } }示例:更新索引
user_data中ID为123的文档的age字段为30:POST /user_data/_update/123 { "doc": { "age": 30 } }使用脚本进行动态更新
如果需要做计算或条件更新,可以用脚本实现。比如给age字段加1:POST /user_data/_update/123 { "script": { "source": "ctx._source.age += params.increment", "params": { "increment": 1 } } }批量更新符合查询条件的文档
用_update_by_query可以批量更新所有匹配指定查询的文档。比如把所有status为active的文档的priority设为high:POST /user_data/_update_by_query { "query": { "term": { "status": "active" } }, "script": { "source": "ctx._source.priority = 'high'" } }
新增字段操作很简单——默认情况下Elasticsearch支持动态字段添加(只要索引的动态映射是开启状态,这是默认配置)。
给单个文档新增字段
在_update请求的doc参数中直接添加新字段即可:POST /your_index_name/_update/your_document_id { "doc": { "Name": "A" } }这个操作会给目标文档新增
Name: "A"字段,同时保留原有的id等字段。批量给多个文档新增字段
用_update_by_query可以给所有文档或符合特定条件的文档批量添加字段。比如给索引中所有文档新增Name: "A":POST /your_index_name/_update_by_query { "query": { "match_all": {} }, "script": { "source": "ctx._source.Name = 'A'" } }如果只想给
id大于100的文档新增字段,可以调整查询条件:POST /your_index_name/_update_by_query { "query": { "range": { "id": { "gt": 100 } } }, "script": { "source": "ctx._source.Name = 'A'" } }静态映射索引的注意事项
如果你的索引设置了dynamic: false(禁用自动字段添加),需要先更新索引的映射,提前定义新字段:PUT /your_index_name/_mapping { "properties": { "Name": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } }完成映射更新后,再执行前面的字段新增操作即可。
内容的提问来源于stack exchange,提问作者Suraj

