Monday 5 October 2015

Elasticsearch: Create new document if document is not exist

Some times you want to create a document, if it not exist, how to do that.

Approach 1:
First you check whether document is exist or not using HEAD request, if document not exist create new one.

Approach 2
Using query parameter 'op_type'.

PUT xyz/employees/1?op_type=create


Above statement creates document, if it is not exist; else it throws DocumentAlreadyExistsException.

PUT xyz/employees/1?op_type=create
{
  "firstName":"PTR",
  "lastName" : "Nayan"
}

Above snippet throws DocumentAlreadyExistsException, since document with id 1 is already exist.

{
   "error": "DocumentAlreadyExistsException[[xyz][2] [employees][1]: document already exists]",
   "status": 409
}

Approach 3
Use _create end point.
PUT xyz/employees/1/_create

Above statement creates document, if it is not exist; else it throws DocumentAlreadyExistsException.

PUT xyz/employees/1/_create
{
  "firstName":"PTR",
  "lastName" : "Nayan"
}


Above snippet throws DocumentAlreadyExistsException, since document with id 1 is already exist..

{
   "error": "DocumentAlreadyExistsException[[xyz][2] [employees][1]: document already exists]",
   "status": 409
}





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment