Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to a Elasticsearch field list/array if it's not an existing element

Say we have:

curl -XPOST "http://localhost:9200/t/t/1" -d'
{
     "hobbies" : ["a", "b"]
}'

I know I can do this to append to hobbies:

curl -XPOST "http://localhost:9200/t/t/1/_update" -d'
{
     "script" : "ctx._source.hobbies += hobby",
     "params" : {
         "hobby" : "c"
     }
}'

But how can I do it so if hobby isn't 'c' but is 'b', I won't end up with ["a", "b", "b"] for hobby? So it only appends "c" if "c" isn't a hobby already?

like image 379
Hard worker Avatar asked Jun 30 '15 15:06

Hard worker


1 Answers

You can achieve the same by modifying the script in OP a little

Example :

curl -XPOST "http://localhost:9200/t/t/1/_update -d'
{
     "script" : " if(! ctx._source.hobbies.contains(hobby)){ ctx._source.hobbies += hobby }",
     "params" : {
         "hobby" : "c"
     }
}'

The above example assumes that field hobbies exists and is a List else you would need to incorporate a bit more logic to handle these.

like image 176
keety Avatar answered Sep 20 '22 15:09

keety