Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rename array values in elastic search

I have an array in elastic search document. I want to rename all occurrences of a particular value. It has the following mapping

{
  "products" : {
    "mappings" : {
      "properties" : {
        "inStock" : {
          "type" : "long"
        },
        "name" : {
          "type" : "keyword"
        },
        "price" : {
          "type" : "double"
        },
        "tags" : {
          "type" : "keyword"
        }
      }
    }
  }
}
{
  "_index" : "products",
  "_type" : "_doc",
  "_id" : "100",
  "_version" : 6,
  "_seq_no" : 5,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "Product A",
    "price" : 50,
    "inStock" : 5,
    "tags" : [
      "tagA",
      "tagB",
      "tagC",
      "tagD",
      "tagB"
    ]
  }
}

I am looking for a query to rename tagB to something else, for eg: tagF in all documents which has this matching tag.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can replace the contents of an array with an update_by_query with a simple script as follows.

POST /products/_update_by_query
{
  "query": {
    "term": {
      "tags": {
        "value": "tagB"
      }
    }
  },
  "script": {
    "source": "Collections.replaceAll(ctx._source.tags, params.oldTag, params.newTag);",
    "params": {"oldTag": "tagB", "newTag": "tagF"}, 
    "lang": "painless"
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading