Looking for Elasticsearch updateByQuery syntax example (Node driver)

James Jensen picture James Jensen · Aug 24, 2016 · Viewed 14.5k times · Source

You have an Elasticsearch index with two docs:

[
  {
    "_index": "myIndex",
    "_type": "myType",
    "_id": "es1472002807930",
    "_source": {
      "animal": "turtle",
      "color": "green",
      "weight": 20,
    }
  },
  {
    "_index": "myIndex",
    "_type": "myType",
    "_id": "es1472002809463",
    "_source": {
      "animal": "bear",
      "color": "brown"
      "weight": 400,
    }
  }
]

Later, you get this updated data about the bear:

{
  "color": "pink",
  "weight": 500,
  "diet": "omnivore",
}

So, you want to update the "color" and "weight" values of the bear, and add the "diet" key to the "bear" doc. You know there's only one doc with "animal": "bear" (but you don't know the _id):

Using the Nodejs driver, what updateByQuery syntax would update the "bear" doc with these new values?

(NOTE: this question has been entirely edited to be more useful to the SO community!)

Answer

James Jensen picture James Jensen · Aug 26, 2016

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)
        }
    )