在Elasticsearch中,可以使用_update
API实现文档的部分更新。部分更新允许您仅修改文档中的一些字段而无需替换整个文档。以下是部分更新文档的示例:
POST /my_index/_doc/1/_update
{
"doc": { // 或者 "scripted_upsert": true,
"field_to_update": "new value"
}
}
在上面的请求中,我们试图更新索引my_index
中ID为1
的文档的field_to_update
字段。doc
关键字后面的对象包含了我们要修改的字段及其新的值。
如果你想要在文档不存在时插入新文档,可以结合使用scripted_upsert
选项(在Elasticsearch 7.x及以上版本中推荐使用if_exists
参数):
POST /my_index/_doc/1/_update
{
"if_exists": true, // Elasticsearch 7.x+
"doc": {
"field_to_update": "new value"
}
}
或者在老版本中:
POST /my_index/_doc/1/_update
{
"scripted_upsert": true,
"upsert": {
"field1": "initial value if doc doesn't exist",
"field_to_update": "new value"
},
"script": {
"source": "ctx._source.field_to_update = params.new_value",
"params": {
"new_value": "new value"
}
}
}
在上述带scripted_upsert
的例子中,如果文档存在,则会执行更新脚本(这里假设脚本简单地将field_to_update
字段设置为传入的新值),如果文档不存在,则会执行upsert
部分,插入一个全新的文档。
另外,如果只需要对已有字段进行增量操作(如计数器增加),可以使用脚本来实现:
POST /my_index/_doc/1/_update
{
"script": {
"source": "ctx._source.views += params.increment",
"params": {
"increment": 1
}
}
}
在这条请求中,脚本会将文档中的views
字段值增加1。