Search code examples
elasticsearchmvel

elasticsearch update a set


Im trying to update a list fields only if the item is not already in the list.

what's wrong with:

curl -X POST 'http://localhost:9200/my_index/my_doc/id/_update' -d 
'{ "script":
"{if !(ctx._source.my_field contains new_item) {ctx._source.my_field.add(new_item)}}" 
, "params":{"new_item":"hopefully_new_text"}}'

This adds the item anyway, even if it exists.

any smarter way to do it?


Solution

  • That's one of the many strange things about MVEL parsing behavior. If you will remove the outermost { }, you will see that you have a syntax error in your if statement and if you will fix that error, everything will work:

    curl -X POST 'http://localhost:9200/my_index/my_doc/id/_update' -d  '{
        "script": "if (!(ctx._source.my_field contains new_item)) {ctx._source.my_field.add(new_item)}",
        "params": {
            "new_item": "hopefully_new_text"
        }
    }
    '