Update document in Elasticsearch

Documents in Elasticsearch are always immutable we cannot replace or change them directly. If we require updating document in Elasticsearch then we need to reindex or replace it. We can change an existing document by using Index API as well. Elasticsearch delete the old document automatically and add a new document internally.

Updating Document in Elasticsearch

Lets start step by step process to understand how document index and update will work.

Step 1. Add new document

curl -XPUT 'localhost:9200/roopendra/post/1' -d '{
    "title" : "Test this test post",
    "text": "Testing update",
    "date": "2015-10-04 12:22:22"
 }'

Response:

{
    "_index": "roopendra",
    "_type": "post",
    "_id": "1",
    "_version": 1,
    "created": true
}

In first time elasticsearch assign _version to the document and “created” flag is true.

Step 2: Update already index document:

curl -XPUT 'localhost:9200/roopendra/post/1' -d '{
    "title" : "Test this test post",
    "text": "Testing update document in Elasticsearch",
    "date": "2015-10-04 12:22:22"
 }'

Response:

{
    "_index": "roopendra",
    "_type": "post",
    "_id": "1",
    "_version": 2,
    "created": false
}

When we update an existing document then elasticsearch internally marked delete old document and create new document. now version of this document is 2 and “created” is false.

Step 3: Add new field in existing document:

We can add new field in existing document. Elasticsearch automatically create mapping for new field.

curl -XPUT 'localhost:9200/roopendra/post/1' -d '{
    "title" : "Test this test post",
    "text": "Testing update document in Elasticsearch",
    "date": "2015-10-04 12:22:22",
    "author": "roop"
 }'

Response:

{
    "_index": "roopendra",
    "_type": "post",
    "_id": "1",
    "_version": 3,
    "created": false
}

Now new field “author” is added in existing document and _version is 3.

Verify document

curl -XGET 'http://localhost:9200/roopendra/post/1/'

Response:

{
    "_index": "roopendra",
    "_type": "post",
    "_id": "1",
    "_version": 3,
    "found": true,
    "_source": {
        "title": "Test this test post",
        "text": "Testing update document in Elasticsearch",
        "date": "2015-10-04 12:22:22",
        "author": "roop"
    }
}

For more details : https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html

(Visited 1,226 times, 22 visits today)