[Recipes] Updating Values in a Nested Array of Objects in Elasticsearch

Problem: 

Need to update value of a field within an object which is an element of a nested array of objects.

Solution Summary: 

One way to update is to replace the nested array as a whole, which is same as any other updates. However if you want to replace just the value of a field within an object which is an element of a nested array of objects, you need to use scripting. 

Prerequisites: 

Working Elasticsearch setup with Kibana.

Data is created based on the accounts data we were working on from here, but you can follow this lab independently as we are setting up data again.

If you are following along from, you will have to delete the index you already created for department:

DELETE department

Solution Steps: 

Data Setup

I will create arrays of employees in two departments, based on the accounts data we were working on from here.

First I will create a mapping to make the type of employees as "nested":

PUT department
{
  "mappings": {
    "_doc": {
      "properties": {
        "employees": {
          "type": "nested" 
        }
      }
    }
  }
}

 

We will add two documents with nested array of objects:

POST /department/_doc/1
{
  "name":"accounts",
  "employees": [
    {
      "firstname": "Garrett",
      "lastname": "Langley",
      "age": 36,
      "gender": "M",
      "address": "331 Bowne Street"
    },
    {
      "firstname": "Mallory",
      "lastname": "Emerson",
      "age": 24,
      "gender": "F",
      "address": "318 Dunne Court"
    }
    ]
}

 

Verify the document as:

GET /department/_doc/1

 

Nested update with scripting (with painless)

POST /department/_doc/1/_update
{
  "script": {
    "lang": "painless",
    "source": """
            for (int i = 0; i < ctx._source.employees.length; ++i) {
              if(ctx._source.employees[i].firstname == params.emp_name) {
                ctx._source.employees[i].age = 35;
              }
            }
""",
    "params": {
      "emp_name": "Garrett"
    }
  }
}

Note: We updated the age of empleyee Garrett from 36 to 35.

Recipe Tags: 

Contact

Please first use the contact form or facebook page messaging to connect.

Offline Contact
We currently connect locally for discussions and sessions at Bangalore, India. Please follow us on our facebook page for details.
WhatsApp (Primary): (+91) 7411174113
Phone (Escalations): (+91) 7411174114

Business newsletter

Complete the form below, and we'll send you an e-mail every now and again with all the latest news.

About

CloudMaterials.com is my latest blog to share my notes and learning materials on Cloud and Data Analytics. My current focus is on Amazon Web Servivces.

I like to write and always try to document what I learn. I believe that knowledge is useless unless you share it; the more you share, the more you learn.

Recent comments

Photo Stream

,