除了創建和替換文檔外,還可以更新文檔。注意,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
