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.
Recent comments