0

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?

John Paul
  • 75
  • 2
  • 8

1 Answers1

0

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

Adam T
  • 1,481
  • 11
  • 20