Search Template
editSearch Template
editSee Search Template documentation
Define your template parameters as a Map<String,Object>
:
Map<String, Object> template_params = new HashMap<>(); template_params.put("param_gender", "male");
You can use your stored search templates in config/scripts
.
For example, if you have a file named config/scripts/template_gender.mustache
containing:
{ "query" : { "match" : { "gender" : "{{param_gender}}" } } }
Create your search template request:
SearchResponse sr = new SearchTemplateRequestBuilder(client) .setScript("template_gender") .setScriptType(ScriptService.ScriptType.FILE) .setScriptParams(template_params) .setRequest(new SearchRequest()) .get() .getResponse();
template name |
|
template stored on disk in |
|
parameters |
|
set the execution context (ie. define the index name here) |
|
execute and get the template response |
|
get from the template response the search response itself |
You can also store your template in the cluster state:
client.admin().cluster().preparePutStoredScript() .setScriptLang("mustache") .setId("template_gender") .setSource(new BytesArray( "{\n" + " \"query\" : {\n" + " \"match\" : {\n" + " \"gender\" : \"{{param_gender}}\"\n" + " }\n" + " }\n" + "}")).get();
To execute a stored templates, use ScriptService.ScriptType.STORED
:
SearchResponse sr = new SearchTemplateRequestBuilder(client) .setScript("template_gender") .setScriptType(ScriptService.ScriptType.STORED) .setScriptParams(template_params) .setRequest(new SearchRequest()) .get() .getResponse();
template name |
|
template stored in the cluster state |
|
parameters |
|
set the execution context (ie. define the index name here) |
|
execute and get the template response |
|
get from the template response the search response itself |
You can also execute inline templates:
sr = new SearchTemplateRequestBuilder(client) .setScript("{\n" + " \"query\" : {\n" + " \"match\" : {\n" + " \"gender\" : \"{{param_gender}}\"\n" + " }\n" + " }\n" + "}") .setScriptType(ScriptService.ScriptType.INLINE) .setScriptParams(template_params) .setRequest(new SearchRequest()) .get() .getResponse();