首页 > 解决方案 > 使用 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"
          }
        }
      ]
    }
  }
}

标签: elasticsearchelastic-stackmustacheelasticsearch-high-level-restclientjsontemplate

解决方案


我终于想出了解决办法。

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;
    }
}

推荐阅读