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 ?

3 Answers 3

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"
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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"                
          }
      }
      ]
    }
  }
}

Comments

0
POST my_index/_update_by_query
{
  "query": {
    "match": {
      "name" : "A"
    }
  },
  "script": {
    "source": "ctx._source.name = params.name",
    "lang": "painless",
    "params": {
      "name":"B"
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.