salvob
salvob

Reputation: 1370

Elasticsearch: add new fields to an existing documents

I would like to add to an existing document matched by a query a new object with new fields.

PUT test/_doc/1
{ 
 "id" : 1,
 "text": "My life is beautiful"
 "category": "optimistic"
}

I would like to add to all the "category":"optimistic" documents, a new object, something like

{"references": {
   "group": "Pro-life",
   "responsable": "Mr. Happy Guy"
   "job": "Happiness bringer"
}

I would like to try with update_by_query but I cannot make it work with object like this. Any ideas?

I did try with this:

{
     "script": "ctx._source.references='{\"hello\":\"world\"}'",
     "query": {
        "match": {
            "category": "optimistic"
        }
     }
} 

But it doesn't give me the expected results. It just saved it as a string """{"hello":"world"}""" whilst I wanted it as JSON object

Upvotes: 2

Views: 2545

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Not tested but you could try with params along with update_by_query,

{
     "query": {
        "match": {
            "category": "optimistic"
        }
     },
     "script": {
       "inline": "ctx._source.references = params.new_fields",
       "params": {
       "new_fields": {
           "group": "Pro-life",
           "responsable": "Mr. Happy Guy"
           "job": "Happyness bringer"
        }
      }
    }
} 

Upvotes: 3

ugosan
ugosan

Reputation: 1586

You should use painless syntax to do that, try it like that:

"script": "ctx._source.references=[ \"hello\":\"world\" ]"

More info: https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-operators-reference.html#map-initialization-operator

Upvotes: 0

Related Questions