PeteyPabPro PeteyPabPro - 5 months ago 114x
Java Question

How to update nested objects in Elasticsearch 2.2 script via Java API

I'm trying to update a nested object in Elasticsearch via the Java API, using a technique similar to what is outlined here. The problem is how to pass the json into the script. If I just blindly concatenate the json to the script string as suggested here, the Groovy does not compile. If you pass it in directly as a parameter, it just gets parsed as a string. If I try to use JsonSlurper, like:

String script = "ctx._source.pete = new groovy.json.JsonSlurper().parseText(json)";
Map<String, Object> params = ImmutableMap.of("json", json);
return new Script(script, ScriptService.ScriptType.INLINE, null, params);

I get a compilation exception: unable to resolve class groovy.json.JsonSlurper

A further problem with the JsonSlurper approach seems to be that the Elasticsearch team has basically disabled it in 2.2.

Does anyone know how to pass the json in correctly via the Java API?


Thanks to the guys at Elasticsearch for helping me with this. The answer is to convert the JSON to a Map and then just pass the Map as a param:

String script = "ctx._source.pete = jsonMap";
Map<? ,?> jsonMap = new ObjectMapper().readValue(json, HashMap.class);
Map<String, Object> params = ImmutableMap.of("jsonMap", jsonMap);
return new Script(script, ScriptService.ScriptType.INLINE, null, params);

I'm using to do the conversion from JSON to the Map.