Aero Wang
Aero Wang

Reputation: 9267

elasticsearch.js: updateByQuery if exist otherwise insert

Using elasticsearch.js (node.js) SDK we could use client.index({ ... }) to upsert a document (insert if not existed otherwise update).

However if I only want to update a specific field for example like this:

client.updateByQuery({
  index: 'test',
  body: {
    query: { match: { _id: '1' } },
    script: { inline: 'ctx._source.hello = "world"' }
  }
})

Now I want to create a document with id 1 if it doesn't exist with its field hello set to world or if document with id 1 exists then update its hello field to world. Is this possible? How?

Upvotes: 0

Views: 1183

Answers (1)

Nishant
Nishant

Reputation: 7874

You are probably looking for update API with doc as update. Use as below:

POST test/_update/1
{
  "doc":{
    "hello": "world"
  },
  "doc_as_upsert": true
}

Upvotes: 1

Related Questions