12

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?

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.