5

I have an index already filled with many documents.
All of the documents in the index have a name string field.
I want to query and update all of them which have name = A and set it to name = B.

For clarity, in SQL it would be something like :
UPDATE FROM table SET name = 'B' WHERE name = 'A';

With elasticsearch API, according to the docs : https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html

I tried this query :

POST my_index/_update_by_query
{
  "script": {
    "inline": "ctx._source.name = 'B'",
    "lang": "painless"
  },
  "query": {
    "term": {
      "name" : "A"
    }
  }
}

However it just returns that nothing was modified. I can still find document with name=A, so they were not edited.

{
  "took": 1,
  "timed_out": false,
  "total": 0,
  "updated": 0,
  "deleted": 0,
  "batches": 0,
  "version_conflicts": 0,
  "noops": 0,
  "retries": {
    "bulk": 0,
    "search": 0
  },
  "throttled_millis": 0,
  "requests_per_second": -1,
  "throttled_until_millis": 0,
  "failures": []
}

Any idea why my _update_by_query doesn't do anything ?

2 Answers 2

7

Found it, my string field was an analysed field, so I must use a match query like this :

POST my_index/_update_by_query
{
  "script": {
    "inline": "ctx._source.name = 'B'",
    "lang": "painless"
  },
  "query": {
    "match": {
      "name" : "A"
    }
  }
}
1

You can use ctx._source.put function like shown below

POST /my_index/_update_by_query
{
  "script": {
    "source": """
     ctx._source.put('name','B');    
     """,
     "lang": "painless"
  }
  ,
  "query": {
    "bool": {
      "must": [
      {
          "match": {
          "name" : "A"                
          }
      }
      ]
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.