Casey Johnson Casey Johnson - 6 months ago 15
JSON Question

Converting Elastic Search field to Array

In elastic search if you have document that has a pre-existing array

"movies": [
"Back to the Future"
]


And then you update it to add more movies like such

{
"script" : "ctx._source.movies += tag",
"params" : {
"tag" : "Pulp Fiction"
}
}


Then the value is added to the field. That works great... but what if the field isn't an arry to start with and instead looks like this

"movies": "Back to the Future"


If you run the same script you will get the following result

"movies":"Back to the FuturePulpFiction"


So my question is how do I take this existing field and "convert" it to an array to tell elastic search that I want to think of it as an array?

Val Val
Answer

You can use this script instead. It checks whether movies is an array and if not it creates one

{
  "script" : "if (ctx._source.movies.getClass().isArray()) { ctx._source.movies += tag } else { ctx._source.movies = [ctx._source.movies, tag] }",
  "params" : {
    "tag" : "Pulp Fiction"
  }      
}

Another shorter way of doing it is to always assign an array and then "flatten" it using Groovy's Collection.flatten() method

{
  "script" : "ctx._source.movies = [ctx._source.movies, tag].flatten()}",
  "params" : {
    "tag" : "Pulp Fiction"
  }      
}