elasticsearch - 使用 Mustache API 解析 Elasticsearch JSON 模板请求
问题描述
我一直在使用SearchTemplateRequest类来执行我的请求,它使用 Mustache 模板来解析带有传递参数的模板字符串。
Elasticsearch 模板 - 将参数转换为 JSON
但是,我必须更改我将切换到 Java 低级客户端的实现。我想使用 SearchTemplateRequest 在内部使用的 Mustache 实现来解析模板。我可以使用 Mustache 依赖项或使用它的 Elasticsearch 实现。有人可以帮我吗?
我的模板字符串:
{
"query": {
"bool": {
"filter": "{{#toJson}}clauses{{/toJson}}"
}
}
}
我的参数对象:
{
"clauses": [
{
"term": {
"field1": "field1Value"
}
}
]
}
我的测试代码:
StringWriter writer = new StringWriter();
MustacheFactory mustacheFactory = new DefaultMustacheFactory();
mustacheFactory.compile(new StringReader(requestTemplate), "templateName").execute(writer, params);
writer.flush();
上面的代码向我返回了请求模板字符串,其中空字符串替换了模板。
返回响应:
{
"query": {
"bool": {
"filter": ""
}
}
}
预期反应:
{
"query": {
"bool": {
"filter": [
{
"term": {
"field1": "field1Value"
}
}
]
}
}
}
解决方案
我终于想出了解决办法。
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.TemplateScript;
import org.elasticsearch.script.mustache.MustacheScriptEngine;
import java.util.Map;
import static java.util.Collections.singletonMap;
public class CustomMustacheScriptEngine {
private final String JSON_MIME_TYPE_WITH_CHARSET = "application/json; charset=UTF-8";
private final String JSON_MIME_TYPE = "application/json";
private final String PLAIN_TEXT_MIME_TYPE = "text/plain";
private final String X_WWW_FORM_URLENCODED_MIME_TYPE = "application/x-www-form-urlencoded";
private final String DEFAULT_MIME_TYPE = JSON_MIME_TYPE;
private final Map<String, String> params = singletonMap(Script.CONTENT_TYPE_OPTION, JSON_MIME_TYPE_WITH_CHARSET);
public String compile(String jsonScript, final Map<String, Object> scriptParams) {
jsonScript = jsonScript.replaceAll("\"\\{\\{#toJson}}", "{{#toJson}}").replaceAll("\\{\\{/toJson}}\"", "{{/toJson}}");
final ScriptEngine engine = new MustacheScriptEngine();
TemplateScript.Factory compiled = engine.compile("ScriptTemplate", jsonScript, TemplateScript.CONTEXT, params);
TemplateScript executable = compiled.newInstance(scriptParams);
String renderedJsonScript = executable.execute();
return renderedJsonScript;
}
}
推荐阅读
- android - 新的 gradle 插件版本(4.1.0):不再返回任何资源字段
- regex - 使用 sed 跳过一行的一部分
- javascript - PIXI 图形“内存不足”
- html - 有没有办法让 3 个 div 并排并用 Bootstrap 4 做出响应?
- node.js - npm 错误!对 http://registry.npmjs.org/express 的网络请求失败,原因:连接 ETIMEDOUT
- javascript - ArcGIS API for JavaScript:从动态填充的下拉列表中查询
- django - 如何覆盖 Django 管理员 delete_selected_confirmation.html
- java - 在这个三元语句中可能抛出 NullPointerException 的原因是什么?
- javascript - 如果示例数据结构被认为是一个链接列表,那么如何编写一个打印出其所有成员的函数?
- jpa - 批量更新后的 JPA JQL 查询看到过时的值