简体   繁体   中英

Add additional attribute to an existing document if the attribute doesn't exist elasticsearch

I have a specific requirement were I have to add an additional attribute to elastic search index which has n documents. This has to be done only if the documents don't contain the attribute. This tasks basically involves 2 steps

1) searching 2) updating

I know how to do this with multiple queries. But it would be great if I manage to do this in a single query. Is it possible? If yes, can someone tell me how this can be done.

You can use update by query combined with the exists query to update and add the new field to only those documents which does not contain the attribute.

For example, you have only one documents containing field attrib2 , others don't have that field.

curl -XPUT "http://localhost:9200/my_test_index/doc/1" -H 'Content-Type: application/json' -d'
{
  "attrib1": "value1"
}'
curl -XPUT "http://localhost:9200/my_test_index/doc/2" -H 'Content-Type: application/json' -d'
{
  "attrib1": "value21"
}'
curl -XPUT "http://localhost:9200/my_test_index/doc/3" -H 'Content-Type: application/json' -d'
{
  "attrib1": "value31",
  "attrib2": "value32"
}'

The following update by query will do the job.

curl -XPOST "http://localhost:9200/my_test_index/_update_by_query" -H 'Content-Type: application/json' -d'
{
  "script": {
    "lang": "painless",
    "source": "ctx._source.attrib2 = params.attrib2",
    "params": {
      "attrib2": "new_value_for_attrib2"
    }
  },
  "query": {
    "bool": {
      "must_not": [
        {
          "exists": {
            "field": "attrib2"
          }
        }
      ]
    }
  }
}'

It will set the new value new_value_for_attrib2 to the field attrib2 on only those documents which don't already have that field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM