90 lines
2.8 KiB
Plaintext
90 lines
2.8 KiB
Plaintext
[[java-query-dsl-template-query]]
|
|
==== Template Query
|
|
|
|
See {ref}/search-template.html[Search Template] documentation
|
|
|
|
In order to use the `template` query from the Java API
|
|
the lang-mustache module dependency should be on the classpath and
|
|
the transport client should be loaded with the lang-mustache plugin:
|
|
|
|
[source,java]
|
|
--------------------------------------------------
|
|
TransportClient transportClient = TransportClient.builder()
|
|
.settings(Settings.builder().put("node.name", "node"))
|
|
.addPlugin(MustachePlugin.class)
|
|
.build();
|
|
transportClient.addTransportAddress(
|
|
new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300))
|
|
);
|
|
--------------------------------------------------
|
|
|
|
Define your template parameters as a `Map<String,Object>`:
|
|
|
|
[source,java]
|
|
--------------------------------------------------
|
|
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:
|
|
|
|
[source,js]
|
|
--------------------------------------------------
|
|
{
|
|
"template" : {
|
|
"query" : {
|
|
"match" : {
|
|
"gender" : "{{param_gender}}"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
--------------------------------------------------
|
|
// NOTCONSOLE
|
|
|
|
Define your template query:
|
|
|
|
[source,java]
|
|
--------------------------------------------------
|
|
QueryBuilder qb = new TemplateQueryBuilder(
|
|
"gender_template", <1>
|
|
ScriptService.ScriptType.FILE, <2>
|
|
template_params); <3>
|
|
--------------------------------------------------
|
|
<1> template name
|
|
<2> template stored on disk in `gender_template.mustache`
|
|
<3> parameters
|
|
|
|
You can also store your template in the cluster state:
|
|
|
|
[source,java]
|
|
--------------------------------------------------
|
|
client.admin().cluster().preparePutStoredScript()
|
|
.setScriptLang("mustache")
|
|
.setId("template_gender")
|
|
.setSource(new BytesArray(
|
|
"{\n" +
|
|
" \"template\" : {\n" +
|
|
" \"query\" : {\n" +
|
|
" \"match\" : {\n" +
|
|
" \"gender\" : \"{{param_gender}}\"\n" +
|
|
" }\n" +
|
|
" }\n" +
|
|
" }\n" +
|
|
"}")).get();
|
|
--------------------------------------------------
|
|
|
|
To execute a stored templates, use `ScriptService.ScriptType.STORED`:
|
|
|
|
[source,java]
|
|
--------------------------------------------------
|
|
QueryBuilder qb = new TemplateQueryBuilder(
|
|
"gender_template", <1>
|
|
ScriptType.STORED, <2>
|
|
template_params); <3>
|
|
--------------------------------------------------
|
|
<1> template name
|
|
<2> template stored in the cluster state
|
|
<3> parameters
|