Search in sources :

Example 1 with TemplateScript

use of org.opensearch.script.TemplateScript in project OpenSearch by opensearch-project.

the class CustomMustacheFactoryTests method testUrlEncoder.

public void testUrlEncoder() {
    final ScriptEngine engine = new MustacheScriptEngine();
    final Map<String, String> params = singletonMap(Script.CONTENT_TYPE_OPTION, X_WWW_FORM_URLENCODED_MIME_TYPE);
    TemplateScript.Factory compiled = engine.compile(null, "{\"field\": \"{{value}}\"}", TemplateScript.CONTEXT, params);
    TemplateScript executable = compiled.newInstance(singletonMap("value", "tilde~ AND date:[2016 FROM*]"));
    assertThat(executable.execute(), equalTo("{\"field\": \"tilde%7E+AND+date%3A%5B2016+FROM*%5D\"}"));
}
Also used : ScriptEngine(org.opensearch.script.ScriptEngine) TemplateScript(org.opensearch.script.TemplateScript)

Example 2 with TemplateScript

use of org.opensearch.script.TemplateScript in project OpenSearch by opensearch-project.

the class MustacheTests method testBasics.

public void testBasics() {
    String template = "GET _search {\"query\": " + "{\"boosting\": {" + "\"positive\": {\"match\": {\"body\": \"gift\"}}," + "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}" + "}}, \"negative_boost\": {{boost_val}} } }}";
    Map<String, Object> params = singletonMap("boost_val", "0.2");
    TemplateScript.Factory factory = engine.compile(null, template, TemplateScript.CONTEXT, Collections.emptyMap());
    TemplateScript result = factory.newInstance(params);
    assertEquals("Mustache templating broken", "GET _search {\"query\": {\"boosting\": {\"positive\": {\"match\": {\"body\": \"gift\"}}," + "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}}}, \"negative_boost\": 0.2 } }}", result.execute());
}
Also used : Matchers.emptyOrNullString(org.hamcrest.Matchers.emptyOrNullString) Matchers.containsString(org.hamcrest.Matchers.containsString) TemplateScript(org.opensearch.script.TemplateScript)

Example 3 with TemplateScript

use of org.opensearch.script.TemplateScript in project OpenSearch by opensearch-project.

the class TransportRankEvalAction method doExecute.

@Override
protected void doExecute(Task task, RankEvalRequest request, ActionListener<RankEvalResponse> listener) {
    RankEvalSpec evaluationSpecification = request.getRankEvalSpec();
    EvaluationMetric metric = evaluationSpecification.getMetric();
    List<RatedRequest> ratedRequests = evaluationSpecification.getRatedRequests();
    Map<String, Exception> errors = new ConcurrentHashMap<>(ratedRequests.size());
    Map<String, TemplateScript.Factory> scriptsWithoutParams = new HashMap<>();
    for (Entry<String, Script> entry : evaluationSpecification.getTemplates().entrySet()) {
        scriptsWithoutParams.put(entry.getKey(), scriptService.compile(entry.getValue(), TemplateScript.CONTEXT));
    }
    MultiSearchRequest msearchRequest = new MultiSearchRequest();
    msearchRequest.maxConcurrentSearchRequests(evaluationSpecification.getMaxConcurrentSearches());
    List<RatedRequest> ratedRequestsInSearch = new ArrayList<>();
    for (RatedRequest ratedRequest : ratedRequests) {
        SearchSourceBuilder evaluationRequest = ratedRequest.getEvaluationRequest();
        if (evaluationRequest == null) {
            Map<String, Object> params = ratedRequest.getParams();
            String templateId = ratedRequest.getTemplateId();
            TemplateScript.Factory templateScript = scriptsWithoutParams.get(templateId);
            String resolvedRequest = templateScript.newInstance(params).execute();
            try (XContentParser subParser = createParser(namedXContentRegistry, LoggingDeprecationHandler.INSTANCE, new BytesArray(resolvedRequest), XContentType.JSON)) {
                evaluationRequest = SearchSourceBuilder.fromXContent(subParser, false);
                // check for parts that should not be part of a ranking evaluation request
                validateEvaluatedQuery(evaluationRequest);
            } catch (IOException e) {
                // if we fail parsing, put the exception into the errors map and continue
                errors.put(ratedRequest.getId(), e);
                continue;
            }
        }
        if (metric.forcedSearchSize().isPresent()) {
            evaluationRequest.size(metric.forcedSearchSize().getAsInt());
        }
        ratedRequestsInSearch.add(ratedRequest);
        List<String> summaryFields = ratedRequest.getSummaryFields();
        if (summaryFields.isEmpty()) {
            evaluationRequest.fetchSource(false);
        } else {
            evaluationRequest.fetchSource(summaryFields.toArray(new String[summaryFields.size()]), new String[0]);
        }
        SearchRequest searchRequest = new SearchRequest(request.indices(), evaluationRequest);
        searchRequest.indicesOptions(request.indicesOptions());
        searchRequest.searchType(request.searchType());
        msearchRequest.add(searchRequest);
    }
    assert ratedRequestsInSearch.size() == msearchRequest.requests().size();
    client.multiSearch(msearchRequest, new RankEvalActionListener(listener, metric, ratedRequestsInSearch.toArray(new RatedRequest[ratedRequestsInSearch.size()]), errors));
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TemplateScript(org.opensearch.script.TemplateScript) Script(org.opensearch.script.Script) BytesArray(org.opensearch.common.bytes.BytesArray) IOException(java.io.IOException) IOException(java.io.IOException) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) TemplateScript(org.opensearch.script.TemplateScript) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 4 with TemplateScript

use of org.opensearch.script.TemplateScript in project OpenSearch by opensearch-project.

the class MustacheScriptEngineTests method testParseTemplateAsSingleStringWithConditionalClause.

public void testParseTemplateAsSingleStringWithConditionalClause() throws IOException {
    String templateString = "{" + "  \"source\" : \"{ \\\"match_{{#use_it}}{{template}}{{/use_it}}\\\":{} }\"," + "  \"params\":{" + "    \"template\":\"all\"," + "    \"use_it\": true" + "  }" + "}";
    XContentParser parser = createParser(JsonXContent.jsonXContent, templateString);
    Script script = Script.parse(parser);
    TemplateScript.Factory compiled = qe.compile(null, script.getIdOrCode(), TemplateScript.CONTEXT, Collections.emptyMap());
    TemplateScript TemplateScript = compiled.newInstance(script.getParams());
    assertThat(TemplateScript.execute(), equalTo("{ \"match_all\":{} }"));
}
Also used : Script(org.opensearch.script.Script) TemplateScript(org.opensearch.script.TemplateScript) XContentParser(org.opensearch.common.xcontent.XContentParser) TemplateScript(org.opensearch.script.TemplateScript)

Example 5 with TemplateScript

use of org.opensearch.script.TemplateScript in project OpenSearch by opensearch-project.

the class FactoryTests method testTemplate.

public void testTemplate() {
    TemplateScript.Factory factory = getEngine().compile("template_test", "params['test']", TemplateScript.CONTEXT, Collections.emptyMap());
    TemplateScript script = factory.newInstance(Collections.singletonMap("test", "abc"));
    assertEquals("abc", script.execute());
    assertEquals("abc", script.execute());
    script = factory.newInstance(Collections.singletonMap("test", "def"));
    assertEquals("def", script.execute());
    assertEquals("def", script.execute());
}
Also used : TemplateScript(org.opensearch.script.TemplateScript)

Aggregations

TemplateScript (org.opensearch.script.TemplateScript)9 XContentParser (org.opensearch.common.xcontent.XContentParser)4 Script (org.opensearch.script.Script)4 ScriptEngine (org.opensearch.script.ScriptEngine)3 SearchRequest (org.opensearch.action.search.SearchRequest)2 BytesArray (org.opensearch.common.bytes.BytesArray)2 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Matchers.containsString (org.hamcrest.Matchers.containsString)1 Matchers.emptyOrNullString (org.hamcrest.Matchers.emptyOrNullString)1 MultiSearchRequest (org.opensearch.action.search.MultiSearchRequest)1