Amit's Garage

A garage where one can get tools to solve their problems

Update multiple documents with multiple values

January 9, 2018 by BlakDronzer

PROBLEM

We have yet seen how to update multiple documents in elasticsearch and we have checked how to update data using elasticsearch. But if you see, on both the articles we have been setting up multiple scripts / ingest-pipelines and then running the same for update individually. Means, if we were to update 4 elements in multiple documents, we will create that many scripts / ingest-pipeline and run it that many times. Now what if we could achieve the same in a single go!

SOLUTION

We can create a script that will run in multiple set of instructions, do an update for multiple values. The script currently is at a basic level, you can explore further to do much tedious operations on the same. But none the less – here is a simple set of example that will simplify the developers life.

Here, i just ran into a scenario that for a new client created, i forgot to turn on the flag for activation. Now when i save in all the articles, it sets into the system, gets mapped to a topic but without client / brand information. How to set the same in simple operation? Here is the following solution..

Step 1 – Create the update script


PUT _scripts/update-clientbrand
{
  "script": {
    "lang": "painless",
    "code": "ctx._source.brand_id = params.brand_id; ctx._source.brand_name = params.brand_name; ctx._source.client_id = params.client_id; ctx._source.client_name = params.client_name;"
  }
}

If you notice, we have placed in  – multiple execution statements for updating the document variables with set values. Now lets write in the script that will do the actual updation


POST articles/_update_by_query
{
  "script": {
    "id": "update-clientbrand",
    "params": {
      "brand_id": "12",
      "brand_name": "Some Brand Name",
      "client_id": "100003",
      "client_name": "Some Client Name"
    }
  },
  "query": {
    "match" : {
      "topic_name": "Some Topic Name"
    }
  }
}

Now this will update all the documents that gets hits up by this query and update the brand / client details.

Share :  

1447   BlakDronzer    Elastic Search  
Total 0 Votes:
0
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Related Knowledge Base Posts -

  • Percolator, a powerful tool from elasticsearch
  • Install and create a cluster of ES Servers
  • Eased out solution for people using elasticsearch
  • Search Knowledgebase