正如doc所述,我们可以使用搜索模板通过java API向elasticsearch服务器发送请求:
@Test
public void testTemplateQuery2() {
Map<String, Object> template_params = new HashMap<>();
template_params.put("query_string", "aaa bbb");
StreamInput in;
SearchRequestBuilder builder = client.prepareSearch()
.setTemplateName("template_gender")
.setTemplateType(ScriptService.ScriptType.FILE)
.setTemplateParams(template_params);
SearchResponse searchResponse = builder.get();
System.out.println(searchResponse);
}
通过这种方式,我应该在 elasticsearch server (/opt/elasticsearch-1.5.2/config/scripts/template_gender.mustache)中创建一个文件:
{
"size" : 1,
"_source" : ["timestamp"],
"query": {
"match": {
"field1": "{{query_string}}"
}
}
}
但是我想在我的java端配置它,我尝试了这个:
@Test
public void testTemplateQuery3() {
Map<String, Object> template_params = new HashMap<String, Object>();
template_params.put("query_string", "aaa");
SearchRequestBuilder builder = client.prepareSearch().setTimeout(TimeValue.timeValueMinutes(5))
.setTemplateType(ScriptService.ScriptType.INLINE)
.setTemplateSource("{'template' : {'size' : 1, '_source' : ['timestamp','field1'], 'query': { 'match': { 'field1': '{{query_string}}'}}}}".replace('\'', '"'))
.setTemplateParams(template_params);
SearchResponse searchResponse = builder.get();
System.out.println(searchResponse);
}
但是查询在服务器中解析如下:
{"size":1,"_source":["timestamp","field1"],"query":{"match":{"field1":""}}}
“query_string”被解析为空字符串“”,为什么?