0
votes

I have a use case of elastic search to update a doc.

My doc is something like this-

{
"first_name" : "firstName",
"last_name" : "lastName",
"version"  : 1234,
"user_roles" : {
   "version" : 12345,
    "id" : 1234, 
    "name" : "role1"},
},
"groups" : {
  "version" : 123,
 "list": [
 {"id":123, "name" : "ashd"},
 {"id":1234, "name" : "awshd"},
]
}

}

Now depepeding on some feed I will either will be updating the parent doc or will be updating the nested doc.

I am able to find how to update the basic attributes like firstName and lastName but unable to get how to update complex/nested ones

I did something like from REST client-

"script": {
    "inline": "ctx._source.user_roles = { "id" : 5678, "name" :"hcsdl"}
    }

but its giving me exception-

Actual use case- I will actually be getting a Map in java. This key can be simple key like "first_name" or can be complex key like "user_role" and "groups" I want to update the document using update by query on version.

The code I wrote is something like-

for (String key : document.keySet()) {

            String value = defaultObjectMapper.writeValueAsString(document.get(key));

            scriptBuilder.append("ctx._source.");
            scriptBuilder.append(key);
            scriptBuilder.append('=');
            scriptBuilder.append(value);
            scriptBuilder.append(";");
        }

where document is the Map Now I might get the simple fields to update or complex object. I tried giving keys like user_roles.id and user_roles.name and also tried giving complete user_roles but nothing is working.

Can someone helpout

1
What exception do you get? You probably need to escape the double quotes. - Val

1 Answers

0
votes

Try this with groovy maps instead of verbatim JSON inside your script:

"script": {
   "inline": "ctx._source.user_roles = [ 'id' : 5678, 'name' : 'hcsdl']}
}