How can I add element to array in ElasticSearch only if it doesn't exist?

734 Views Asked by At

How can I add an user to elastic search only if the user doesn't exists as well as user count?

    {
            "script" : {
                "source": "if (ctx._source.users != null){ctx._source.user_count += params.count;  ctx._source.users.add(ctx._source.users.indexOf(params.user))}",
                "lang": "painless",
                "params" : {
                    "user" : "user123",
                    "count": 1
                }
            }
        }

In the above code, I'm just adding user without checking whether the user already exists which can result in multiple elements with same username.

Is it possible to add only if user does not exists?

1

There are 1 best solutions below

0
Adam T On

For a normal put operation you can add query parameter op_type=create which causes the put to fail if a document with that ID already exists.

For example, this would fail if user with ID 1 already exists:

PUT users/_doc/1?op_type=create
{
    "user" : "user1",
    "department" : "IT"
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#operation-type