Search code examples
javagroovyelasticsearchelasticsearch-java-api

How Groovy script can be invoked using java api for Elasticsearch


Looking for pointers to know how Groovy script can be invoked using java api.

test.groovy

def value = dynamicValue    
return value

Want to translate following query in Java:

GET /test-index/_search
{
   "query": {
      "match_all": {}
   },
   "script_fields": {
      "checkValue": {
         "script": "test",
         "params": {
            "dynamicValue": 7
         }
      }
   }
}

Solution

  • You can do it like this:

    Map<String, Object> params = ImmutableMap.of("dynamicValue", 7);
    SearchResponse response = client().prepareSearch("test-index")
            .setQuery(matchAllQuery())
            .addScriptField("checkValue", new Script("test", ScriptType.FILE, "groovy", params))
            .execute().actionGet();
    

    You need to store your test.groovy file in the config/scripts folder on each data node and also make sure scripting is enabled in config/elasticsearch.yml with

    script.inline: on
    script.file: on