Update API

The update API is useful for updating the existing document by ID.

The format of an update request is POST <index>/<type>/<id>/_update, with a JSON request as the body:

POST /catalog/_update/1
{
"doc": {
"price": "28.99"
}
}

The properties specified under the doc element are merged into the existing document. The previous version of this document with an ID of 1 had a price of 26.99. This update operation just updates the price and leaves the other fields of the document unchanged. This type of update means that doc is specified and used as a partial document to merge with an existing document; there are other types of updates supported.

The response of the update request is as follows:

{
"_index": "catalog",
"_type": "_doc",
"_id": "1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}

Internally, Elasticsearch maintains the version of each document. Whenever a document is updated, the version number is incremented.

The partial update that we saw in the preceding code will work only if the document existed beforehand. If the document with the given ID did not exist, Elasticsearch will return an error saying that the document is missing. Let's understand how to do an upsert operation using the update API. The term upsert loosely means update or insert, that is, update the document if it exists, otherwise, insert the new document.

The doc_as_upsert parameter checks whether the document with the given ID already exists and merges the provided doc with the existing document. If the document with the given ID doesn't exist, it inserts a new document with the given document contents.

The following example uses doc_as_upsert to merge into the document with an ID of 3 or insert a new document if it doesn't exist:

POST /catalog/_update/3
{
"doc": {
"author": "Albert Paro",
"title": "Elasticsearch 5.0 Cookbook",
"description": "Elasticsearch 5.0 Cookbook Third Edition",
"price": "54.99"
},
"doc_as_upsert": true
}

We can update the value of a field based on the existing value of that field or another field in the document. The following update uses an inline script to increase the price by two for a specific product:

POST /catalog/_update/1ZFMpmoBa_wgE5i2FfWV
{
"script": {
"source": "ctx._source.price += params.increment",
"lang": "painless",
"params": {
"increment": 2
}
}
}

Scripting support allows you to read the existing value, increment the value by a variable, and store it in a single operation. The inline script that's used here is Elasticsearch's own painless scripting language. The syntax for incrementing an existing variable is similar to most other programming languages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset