Search code examples
hadoopelasticsearchelasticsearch-plugin

Elastic search 5.4 Update \ add nested document


{
        "id":100,
        "name":"xxx",
        "others":{
            "hobbies":["cricket","footbal"]
        }}
  1. How to add new value in hobbies ("hobbies":["cricket","footbal","reading books"])
  2. How add new field in others (ex : location)
  3. How to remove "cricket from hobbies.

Solution

  • You can user scripted update(documentation link) for your requirement.

    1. Query to add value in hobbiles

      {
          "script" : {
              "source": "ctx._source.others.hobbies.add(params.hobby)",
              "lang": "painless",
              "params" : {
              "hobby": "reading books"
           }
         }
      }
      


    2. Adding a new field in others

      {
          "script": {
              "source": "ctx._source.others.location = 'value_of_new_field'",
              "lang": "painless"
          }
      }
      


    3. Remove cricket from hobbies

      {
          "script" : {
              "source": "int index = ctx._source.others.hobbies.indexOf(params.remove_string); if(index != -1){ctx._source.others.hobbies.remove(index);}",
              "lang": "painless",
              "params" : {
                  "remove_string" : "cricket"
              }
          }
      }
      



    UPDATE-1 As per asked in comments below is way to add an array field.

    Adding an array field

        {
            "script": {
                "source": "ctx._source.extra.location = []",
                "lang": "painless"
            }
        }