Elasticsearch painless script not replacing the nested object field value using if condition

后端 未结 1 1634
名媛妹妹
名媛妹妹 2021-01-14 21:10

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:

         


        
相关标签:
1条回答
  • 2021-01-14 21:23

    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.

    Bulk Update - Using _update_by_query

    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
    
      }}
    }
    

    Per Document Update - Using document id

    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!

    0 讨论(0)
提交回复
热议问题