Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Elasticsearch updateByQuery syntax example (Node driver)

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

like image 956
James Jensen Avatar asked Aug 24 '16 02:08

James Jensen


People also ask

How do I write a script in Elasticsearch?

Wherever scripting is supported in the Elasticsearch APIs, the syntax follows the same pattern; you specify the language of your script, provide the script logic (or source), and add parameters that are passed into the script: "script": { "lang": "...", "source" | "id": "...", "params": { ... } }

How do I find Elasticsearch document ID?

The _id field is part of the document metadata and is the unique id for the document in the index. If an id is not provided when a document is indexed, Elasticsearch will generate an id for the document. Without the id, the best that can be done is to search for documents as in your example, and return the id.


1 Answers

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)
        }
    )
like image 167
James Jensen Avatar answered Oct 05 '22 16:10

James Jensen