2

please is possible to append some element to elasticsearch field if types doesn't match? If I have document like this:

{
"counter" : 1,
"tags" : "red"
}

and i want to append another tag field f.e "blue" like this:

{
"script" : {
    "source": "ctx._source.counter += params.newTag",
    "lang": "painless",
    "params" : {
        "newTag" : "blue"
    }
}
}

and i want to have result similar to:

{
"counter" : 1,
"tags" : ["red", "blue"]
 }

i know this:

"source": "ctx._source.counter += params.newTag"

is used for append string to another string

and this:

"source": "ctx._source.counter.add(params.newTag)"

for appending another element to list. So is there any way how to append another element to string field ? Thank You for any suggestions.

user1439198
  • 37
  • 2
  • 8

1 Answers1

8

What you can do is to add a test for the type of your tags field and transform it to an array if it is not. This script should help.

{
   "script" : {
     "source": "if (!(ctx._source.tags instanceof List)) {ctx._source.tags = [ctx._source.tags]} ctx._source.tags += params.newTag",
     "lang": "painless",
     "params" : {
        "newTag" : "blue"
     }
   }
}
TimDog
  • 8,758
  • 5
  • 41
  • 50
Val
  • 207,596
  • 13
  • 358
  • 360