Append element to Eslasticsearch field

2019-08-31 18:28发布

问题:

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.

回答1:

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