Assume I have a Document with Nested Document as:
{ "dept_name" : "IT", "dept_code" : "IT", "staffs" : [ { "emp_name" : "A", "emp_id" : "1", "emp_salary" : "10000" }, { "emp_name" : "B", "emp_id" : "2", "emp_salary" : "20000" }, { "emp_name" : "C", "emp_id" : "3", "emp_salary" : "30000" } ] }
Now, I need to add to the Nested type "staffs", which I have figured out how to do so. Below is the Update code(adding to nested type):
GET dept/dept/1/_update { "script": { "lang": "painless", "inline": "ctx._source.staffs.add(params.dept);", "params": { "dept": { "emp_name" : "D", "emp_id" : "4", "emp_salary" : "40000" } } } }
But what if I need to update a field or two of Nested type. For e.g., I need to update the "emp_salary" to 35000 of "emp_id" = 3.
How this can be achieved? For this I have came up with a method as below(updating existing nested type):
GET dept/dept/1/_update { "script": { "lang": "painless", "inline": """ int i=0; for(LinkedHashMap obj:ctx._source.staffs){ if(obj.id==params.dept.emp_id) { ctx._source.staffs[i]=params.dept; } i++; """, "params": { "dept": { "emp_name" : "C", "emp_id" : "3", "emp_salary" : "35000" } } } }
I'm not sure whether this is an efficient way to do it.
But my main problem is, I can't keep two update commands to achieve both functionalities(Adding new nested docs & updating fields of existing nested docs). I need to combine both into one. It should work like if the nested docs doesn't exists then it should add new nested doc and if it exists then it should update existing nested docs.