Elasticsearch 更新文档


章节


除了创建和替换文档外,还可以更新文档。注意,Elasticsearch实际上并没有在底层执行就地更新,而是先删除旧文档,再添加新文档。

这个例子展示了,把文档(ID为1)中的name字段更改为“Jane Doe”:

API

POST /customer/_update/1?pretty
{
  "doc": { "name": "Jane Doe" }
}

CURL

curl -X POST "localhost:9200/customer/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": { "name": "Jane Doe" }
}
'

这个例子展示了,把文档(ID为1)中的name字段更改为“Jane Doe”,再添加一个年龄字段:

API

POST /customer/_update/1?pretty
{
  "doc": { "name": "Jane Doe", "age": 20 }
}

CURL

curl -X POST "localhost:9200/customer/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": { "name": "Jane Doe", "age": 20 }
}
'

还可以使用简单的脚本执行更新。这个例子使用脚本将年龄增加5岁:

API

POST /customer/_update/1?pretty
{
  "script" : "ctx._source.age += 5"
}

CURL

curl -X POST "localhost:9200/customer/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "script" : "ctx._source.age += 5"
}
'

在上面的例子中,ctx._source引用源文档。

Elasticsearch提供了根据查询条件更新文档的能力(类似SQL update - where语句)。详情参考官网:docs-update-by-query API


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM