How to update a string field with elasticsearch _update_by_query?
Asked Answered
C

3

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 ?

Cush answered 23/6, 2017 at 16:12 Comment(0)
C
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"
    }
  }
}
Cush answered 23/6, 2017 at 16:21 Comment(0)
J
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"                
          }
      }
      ]
    }
  }
}
Jarlathus answered 9/5, 2022 at 10:7 Comment(0)
L
0
POST my_index/_update_by_query
{
  "query": {
    "match": {
      "name" : "A"
    }
  },
  "script": {
    "source": "ctx._source.name = params.name",
    "lang": "painless",
    "params": {
      "name":"B"
    }
  }
}
Luteal answered 30/10, 2023 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.