ShellD
ShellD

Reputation: 85

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.

Upvotes: 0

Views: 253

Answers (1)

Robin Raju
Robin Raju

Reputation: 1325

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

Upvotes: 1

Related Questions