I just started with ES and still leaning the tricks of the trade!!! I need to replace/overwrite one of the fields of a nested object type. Here is the sample doc:
I have mentioned the below queries. (Bulk update
query and per document
update query)
Core piece of logic is in script
, which is same in both queries.
I'd suggest you to go through the logic as it's self explainable. Basically the script iterates through the nested document and depending on the condition you've stated, it would update the count
accordingly.
POST <your_index_name>/_update_by_query
{
"query": {
"match_all": {}
},
"script": {
"lang": "painless",
"source": """
if(ctx._source.ref_counter.contains(params.cur_data)){
for(int i=0; i<ctx._source.ref_counter.size(); i++)
{
HashMap myKV = ctx._source.ref_counter.get(i);
if(myKV.get(params.key_ref)==params.key_ref_value){
myKV.put(params.key_count, params.key_count_value_new);
}
}
//ctx._source.ref_counter.add(params.new_data);
}""",
"params": {
"cur_data": { "ref_name": "test2", "count": 2},
"new_data": { "ref_name": "test2", "count": 22},
"key_ref": "ref_name",
"key_ref_value": "test2",
"key_count": "count",
"key_count_value_new": 80
}}
}
POST <your_index_name>/<your_mapping>/1/_update
{
"script": {
"lang": "painless",
"source": """
if(ctx._source.ref_counter.contains(params.cur_data)){
for(int i=0; i<ctx._source.ref_counter.size(); i++)
{
HashMap myKV = ctx._source.ref_counter.get(i);
if(myKV.get(params.key_ref)==params.key_ref_value){
myKV.put(params.key_count, params.key_count_value_new);
}
}
//ctx._source.ref_counter.add(params.new_data);
}""",
"params": {
"cur_data": { "ref_name": "test2", "count": 2},
"new_data": { "ref_name": "test2", "count": 22},
"key_ref": "ref_name",
"key_ref_value": "test2",
"key_count": "count",
"key_count_value_new": 80
}
}
}
I hope this helps and let me know if you have any queries!