1

My main purpose is to update an existing document in ElasticSearch, via Java High Level REST Client.

For this task, I'm using UpdateByQueryRequest, and sets a Script which modifies the relevant docs.

My question is, if I can set the fields and their new values dynamically:

public Script buildUpdateQueryScript(Map<String,String> updatedValues) {

        String script = "";
       
        updatedFields.forEach((key,value) -> script.concat("ctx._source.").concat(key).concat(" = ").concat(value) );


        return new Script(
            ScriptType.INLINE,
            "painless",
            script,
            Collections.emptyMap()
        );

    }

So for example if my Map contains one element ("keyOne","valueOne"), then script would be as follows:

"ctx._source.keyOne = valueOne"

This is not working of course, I would like to know if this is even possible to build the script dynamically, and if so, what is the right way to do it?

1 Answers1

0

I've found an answer for this, I will post it here so you'll have a reference for similar issues:

Map<String, Object> params = new HashMap<>();
        params.put("keyOne", "valueOne");
        params.put("keyTwo", "valueTwo");


for (String key : params.keySet()) {
            script = script + "ctx._source." + key + " = params." + key + ";";
        }

return new Script(
            ScriptType.INLINE,
            "painless",
            script,
            params
        );