Sunday 18 October 2015

Elasticsearch: Updating documents partially

In this post, I am going to explain how to update a document partially. Elasticsearch provides ‘_update’ endpoint to support partial updates.

For Example
GET xyz/employees/1
Above request return following document.
{
   "_index": "xyz",
   "_type": "employees",
   "_id": "1",
   "_version": 1,
   "found": true,
   "_source": {
      "firstName": "Phalgun",
      "lastName": "Garimella",
      "hobbies": [
         "Watching movies",
         "Stamp collection",
         "Reading books",
         "Playing Cricket"
      ],
      "age": 30
   }
}


I want to update firstName to “Pradeep”, lastName to “Deshala”.

POST xyz/employees/1/_update
{
  "doc":{
    "firstName" : "Pradeep",
    "lastName" : "Deshala"
  }
}


As you observe POST request, we are sending a partial document to “_update” endpoint.

GET xyz/employees/1

{
   "_index": "xyz",
   "_type": "employees",
   "_id": "1",
   "_version": 2,
   "found": true,
   "_source": {
      "firstName": "Pradeep",
      "lastName": "Deshala",
      "hobbies": [
         "Watching movies",
         "Stamp collection",
         "Reading books",
         "Playing Cricket"
      ],
      "age": 30
   }
}


Update hobbies

POST xyz/employees/1/_update
{
  "doc":{
    "hobbies" :[
      "Mobile App development",
      "Gaming"
    ]
  }
}


Now get the document.

GET xyz/employees/1

{
   "_index": "xyz",
   "_type": "employees",
   "_id": "1",
   "_version": 3,
   "found": true,
   "_source": {
      "firstName": "Pradeep",
      "lastName": "Deshala",
      "hobbies": [
         "Mobile App development",
         "Gaming"
      ],
      "age": 30
   }
}


As you observe hobbies are completely overwritten, not appended.

Adding new fields
Suppose you want to add “city” field to document, you just add it using _update endpoint.

POST xyz/employees/1/_update
{
  "doc":{
    "city" : "Bangalore"
  }
}


Now get the document.

GET xyz/employees/1

{
   "_index": "xyz",
   "_type": "employees",
   "_id": "1",
   "_version": 4,
   "found": true,
   "_source": {
      "firstName": "Pradeep",
      "lastName": "Deshala",
      "hobbies": [
         "Mobile App development",
         "Gaming"
      ],
      "age": 30,
      "city": "Bangalore"
   }
}


As you observe city field is added to the document.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment