【问题标题】:Using Mustache API to parse Elasticsearch JSON Template requests使用 Mustache API 解析 Elasticsearch JSON 模板请求
【发布时间】:2020-07-11 09:19:58
【问题描述】:

我一直在使用 SearchTemplateRequest 类来执行我的请求,该类使用 Mustache 模板来解析我的模板字符串和传递的参数。
Elasticsearch Template - Converting Parameters to 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"
          }
        }
      ]
    }
  }
}

【问题讨论】:

    标签: elasticsearch elastic-stack mustache elasticsearch-high-level-restclient jsontemplate


    【解决方案1】:

    我终于找到了解决办法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      相关资源
      最近更新 更多