Elasticsearch update Query using script with params

Hello,

I want to make partial updates by adding an element in my users list:

"users" : [
            {
              "password" : "pwd",
              "level" : "admin",
              "user_name" : "XX",
              "last_name" : "YY",
              "first_name" : "ZZ"
            }
]

using Kibana I've tried this request:

POST my_index/user/1/_update
{
    "script" : {
        "source": "ctx._source.users.add(params.user)",
        "lang": "painless",
        "params" : {
          "user": {
            "user_name" : "user",
            "first_name" : "XX",
            "last_name" : "XX",
            "level" : "simple",
            "password" : "pwd!#"
          }
        }
    }
}

it works fine: 

 "users" : [
                {
                  "password" : "pwd",
                  "level" : "admin",
                  "user_name" : "XX",
                  "last_name" : "YY",
                  "first_name" : "ZZ"
                },
               {
              "password" : "pwd!#",
              "level" : "simple",
              "user_name" : "user",
              "last_name" : "XX",
              "first_name" : "XX"
            }
    ]

I want to do it using java client, I've tried this code:

XContentBuilder builder = XContentFactory.jsonBuilder();
			builder.startObject();
			{
			     builder.field("user_name", user.getUserName());
				 builder.field("first_name", user.getFirstName());
				 builder.field("last_name", user.getLastName());
				 builder.field("level", user.getLevel());
				 builder.field("password", user.getPassword());
			}
			builder.endObject();
			params.put("user", Strings.toString(builder));

UpdateByQueryRequest setScript = request.setScript(
			    new Script(
			        ScriptType.INLINE, "painless",
			        "ctx._source.users.add(params)",			        
			        params)); 
		request.setScroll(TimeValue.timeValueMinutes(10));

 BulkByScrollResponse bulkResponse = restHighLevelClient.updateByQuery(request, RequestOptions.DEFAULT);

as result, I had:

"users" : [
            {
              "password" : "pwd",
              "level" : "admin",
              "user_name" : "XX",
              "last_name" : "YY",
              "first_name" : "ZZ"
            },
            {
              "user" : """{"user_name":"XX","first_name":"XX","last_name":"XX","level":"XX","password":"XX"}""",
              "ctx" : {
                "_routing" : null,
                "_parent" : null,
                "_index" : "administration",
                "_type" : "environnement",
                "_id" : "1",
                "_version" : 24
              }
            }
          ]

so it's not correct, I want to have only user information added to users and I want to do not index ctx informations.

Thanks !

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.