Looking for Elasticsearch updateByQuery syntax example (Node driver) Looking for Elasticsearch updateByQuery syntax example (Node driver) elasticsearch elasticsearch

Looking for Elasticsearch updateByQuery syntax example (Node driver)


The answer was provided by Val in this other SO:

How to update a document based on query using elasticsearch-js (or other means)?

Here is the answer:

    var theScript = {        "inline": "ctx._source.color = 'pink'; ctx._source.weight = 500; ctx._source.diet = 'omnivore';"    }    client.updateByQuery({            index: myindex,           type: mytype,           body: {               "query": { "match": { "animal": "bear" } },               "script": theScript           }        }, function(err, res) {             if (err) {                reportError(err)             }             cb(err, res)        }    )


The other answer is missing the point since it doesn't have any script to carry out the update.

You need to do it like this:

POST /myIndex/myType/_update_by_query{  "query": {     "term": {      "animal": "bear"    }  },  "script": "ctx._source.color = 'green'"}

Important notes:

  • you need to make sure to enable dynamic scripting in order for this to work.
  • if you are using ES 2.3 or later, then the update-by-query feature is built-in
  • if you are using ES 1.7.x or a former release you need to install the update-by-query plugin
  • if you are using anything between ES 2.0 and 2.2, then you don't have any way to do this in one shot, you need to do it in two operations.

UPDATE

Your node.js code should look like this, you're missing the body parameter:

    client.updateByQuery({            index: index,           type: type,           body: {               "query": { "match": { "animal": "bear" } },               "script": { "inline": "ctx._source.color = 'pink'"}           }        }, function(err, res) {             if (err) {                reportError(err)             }             cb(err, res)        }    )


For elasticsearch 7.4 you could use

await client.updateByQuery({  index: "indexName",  body: {    query: {      match: { fieldName: "valueSearched" }    },    script: {      source: "ctx._source.fieldName = params.newValue",      lang: 'painless',      params: {        newValue: "newValue"      }    }  }});