我在 {{ES_HOME}}/config/scripts 中保存了一个模板 foo.mustache。
发布至http://localhost:9200/forward/_search/template具有以下message body
返回有效响应:
{
"template": {
"file": "foo"
},
"params": {
"q": "a",
"hasfilters": false
}
}
既然我已经验证了所有不同的组件的工作原理,我想将其转换为使用 java API。文档 here描述了如何在java中做到这一点:
SearchResponse sr = client.prepareSearch("forward")
.setTemplateName("foo")
.setTemplateType(ScriptService.ScriptType.FILE)
.setTemplateParams(template_params)
.get();
但是,我只想发送一个纯字符串查询(即上面的消息正文的内容),而不是使用 java.lang.String 构建响应。有没有办法做到这一点?我知道对于普通查询,我可以像这样构造它:
SearchRequestBuilder response = client.prepareSearch("forward")
.setQuery("""JSON_QUERY_HERE""")
我相信 setQuery() 方法将内容包装到查询对象中,这不是我想要的模板查询。如果这是不可能的,我只需采用记录的方式并将我的 json 参数转换为 Map<String, Object>
最佳答案
我最终只是将 template_params 转换为 Map<String, Object>
按照文档的要求。我利用 groovy 的 JsonSlurper 通过非常简单的方法将文本转换为对象。
import groovy.json.JsonSlurper
public static Map<String,Object> convertJsonToTemplateParam(String s) {
Object result = new JsonSlurper().parseText(s);
//Manipulate your result if you need to do any additional work here.
//I.e. Programmatically determine value of hasfilters if filters != null
return (Map<String,Object>) result;
}
您可以将以下内容作为字符串传递给此方法:
{
"q": "a",
"hasfilters": true
"filters":[
{
"filter_name" : "foo.untouched",
"filters" : [ "FOO", "BAR"]
},
{
"filter_name" : "hello.untouched",
"list" : [ "WORLD"]
}
]
}
关于java - 通过java API进行elasticsearch的纯字符串模板查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576094/