Search in sources :

Example 1 with ExecutableScript

use of org.elasticsearch.script.ExecutableScript in project elasticsearch by elastic.

the class InternalTemplateService method compile.

@Override
public Template compile(String template) {
    int mustacheStart = template.indexOf("{{");
    int mustacheEnd = template.indexOf("}}");
    if (mustacheStart != -1 && mustacheEnd != -1 && mustacheStart < mustacheEnd) {
        Script script = new Script(ScriptType.INLINE, "mustache", template, Collections.emptyMap());
        CompiledScript compiledScript = scriptService.compile(script, ScriptContext.Standard.INGEST);
        return new Template() {

            @Override
            public String execute(Map<String, Object> model) {
                ExecutableScript executableScript = scriptService.executable(compiledScript, model);
                Object result = executableScript.run();
                if (result instanceof BytesReference) {
                    return ((BytesReference) result).utf8ToString();
                }
                return String.valueOf(result);
            }

            @Override
            public String getKey() {
                return template;
            }
        };
    } else {
        return new StringTemplate(template);
    }
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) BytesReference(org.elasticsearch.common.bytes.BytesReference) Script(org.elasticsearch.script.Script) CompiledScript(org.elasticsearch.script.CompiledScript) ExecutableScript(org.elasticsearch.script.ExecutableScript) ExecutableScript(org.elasticsearch.script.ExecutableScript) Map(java.util.Map)

Example 2 with ExecutableScript

use of org.elasticsearch.script.ExecutableScript in project elasticsearch by elastic.

the class BucketScriptPipelineAggregator method reduce.

@Override
public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext reduceContext) {
    InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket> originalAgg = (InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket>) aggregation;
    List<? extends Bucket> buckets = originalAgg.getBuckets();
    CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS);
    List newBuckets = new ArrayList<>();
    for (Bucket bucket : buckets) {
        Map<String, Object> vars = new HashMap<>();
        if (script.getParams() != null) {
            vars.putAll(script.getParams());
        }
        boolean skipBucket = false;
        for (Map.Entry<String, String> entry : bucketsPathsMap.entrySet()) {
            String varName = entry.getKey();
            String bucketsPath = entry.getValue();
            Double value = resolveBucketValue(originalAgg, bucket, bucketsPath, gapPolicy);
            if (GapPolicy.SKIP == gapPolicy && (value == null || Double.isNaN(value))) {
                skipBucket = true;
                break;
            }
            vars.put(varName, value);
        }
        if (skipBucket) {
            newBuckets.add(bucket);
        } else {
            ExecutableScript executableScript = reduceContext.scriptService().executable(compiledScript, vars);
            Object returned = executableScript.run();
            if (returned == null) {
                newBuckets.add(bucket);
            } else {
                if (!(returned instanceof Number)) {
                    throw new AggregationExecutionException("series_arithmetic script for reducer [" + name() + "] must return a Number");
                }
                final List<InternalAggregation> aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false).map((p) -> {
                    return (InternalAggregation) p;
                }).collect(Collectors.toList());
                aggs.add(new InternalSimpleValue(name(), ((Number) returned).doubleValue(), formatter, new ArrayList<>(), metaData()));
                InternalMultiBucketAggregation.InternalBucket newBucket = originalAgg.createBucket(new InternalAggregations(aggs), (InternalMultiBucketAggregation.InternalBucket) bucket);
                newBuckets.add(newBucket);
            }
        }
    }
    return originalAgg.create(newBuckets);
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) HashMap(java.util.HashMap) DocValueFormat(org.elasticsearch.search.DocValueFormat) ScriptContext(org.elasticsearch.script.ScriptContext) ArrayList(java.util.ArrayList) InternalMultiBucketAggregation(org.elasticsearch.search.aggregations.InternalMultiBucketAggregation) BucketHelpers.resolveBucketValue(org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue) InternalAggregations(org.elasticsearch.search.aggregations.InternalAggregations) Bucket(org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket) Map(java.util.Map) GapPolicy(org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy) StreamSupport(java.util.stream.StreamSupport) AggregationExecutionException(org.elasticsearch.search.aggregations.AggregationExecutionException) Script(org.elasticsearch.script.Script) PipelineAggregator(org.elasticsearch.search.aggregations.pipeline.PipelineAggregator) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) ReduceContext(org.elasticsearch.search.aggregations.InternalAggregation.ReduceContext) List(java.util.List) CompiledScript(org.elasticsearch.script.CompiledScript) InternalSimpleValue(org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue) StreamInput(org.elasticsearch.common.io.stream.StreamInput) ExecutableScript(org.elasticsearch.script.ExecutableScript) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExecutableScript(org.elasticsearch.script.ExecutableScript) ArrayList(java.util.ArrayList) List(java.util.List) InternalMultiBucketAggregation(org.elasticsearch.search.aggregations.InternalMultiBucketAggregation) AggregationExecutionException(org.elasticsearch.search.aggregations.AggregationExecutionException) InternalAggregation(org.elasticsearch.search.aggregations.InternalAggregation) InternalSimpleValue(org.elasticsearch.search.aggregations.pipeline.InternalSimpleValue) InternalAggregations(org.elasticsearch.search.aggregations.InternalAggregations) Bucket(org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with ExecutableScript

use of org.elasticsearch.script.ExecutableScript in project elasticsearch by elastic.

the class ScriptProcessor method execute.

/**
     * Executes the script with the Ingest document in context.
     *
     * @param document The Ingest document passed into the script context under the "ctx" object.
     */
@Override
public void execute(IngestDocument document) {
    ExecutableScript executableScript = scriptService.executable(script, ScriptContext.Standard.INGEST);
    executableScript.setNextVar("ctx", document.getSourceAndMetadata());
    executableScript.run();
}
Also used : ExecutableScript(org.elasticsearch.script.ExecutableScript)

Example 4 with ExecutableScript

use of org.elasticsearch.script.ExecutableScript in project elasticsearch by elastic.

the class ScriptProcessorTests method testScripting.

public void testScripting() throws Exception {
    int randomBytesIn = randomInt();
    int randomBytesOut = randomInt();
    int randomBytesTotal = randomBytesIn + randomBytesOut;
    ScriptService scriptService = mock(ScriptService.class);
    Script script = new Script("_script");
    ExecutableScript executableScript = mock(ExecutableScript.class);
    when(scriptService.executable(any(Script.class), any())).thenReturn(executableScript);
    Map<String, Object> document = new HashMap<>();
    document.put("bytes_in", randomInt());
    document.put("bytes_out", randomInt());
    IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), document);
    doAnswer(invocationOnMock -> {
        ingestDocument.setFieldValue("bytes_total", randomBytesTotal);
        return null;
    }).when(executableScript).run();
    ScriptProcessor processor = new ScriptProcessor(randomAsciiOfLength(10), script, scriptService);
    processor.execute(ingestDocument);
    assertThat(ingestDocument.getSourceAndMetadata(), hasKey("bytes_in"));
    assertThat(ingestDocument.getSourceAndMetadata(), hasKey("bytes_out"));
    assertThat(ingestDocument.getSourceAndMetadata(), hasKey("bytes_total"));
    assertThat(ingestDocument.getSourceAndMetadata().get("bytes_total"), is(randomBytesTotal));
}
Also used : ScriptService(org.elasticsearch.script.ScriptService) Script(org.elasticsearch.script.Script) ExecutableScript(org.elasticsearch.script.ExecutableScript) HashMap(java.util.HashMap) ExecutableScript(org.elasticsearch.script.ExecutableScript) IngestDocument(org.elasticsearch.ingest.IngestDocument)

Example 5 with ExecutableScript

use of org.elasticsearch.script.ExecutableScript in project elasticsearch by elastic.

the class MustacheScriptEngineTests method testSimple.

public void testSimple() throws IOException {
    String templateString = "{" + "\"inline\":{\"match_{{template}}\": {}}," + "\"params\":{\"template\":\"all\"}" + "}";
    XContentParser parser = createParser(JsonXContent.jsonXContent, templateString);
    Script script = Script.parse(parser);
    CompiledScript compiledScript = new CompiledScript(ScriptType.INLINE, null, "mustache", qe.compile(null, script.getIdOrCode(), Collections.emptyMap()));
    ExecutableScript executableScript = qe.executable(compiledScript, script.getParams());
    assertThat(((BytesReference) executableScript.run()).utf8ToString(), equalTo("{\"match_all\":{}}"));
}
Also used : CompiledScript(org.elasticsearch.script.CompiledScript) Script(org.elasticsearch.script.Script) CompiledScript(org.elasticsearch.script.CompiledScript) ExecutableScript(org.elasticsearch.script.ExecutableScript) ExecutableScript(org.elasticsearch.script.ExecutableScript) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

ExecutableScript (org.elasticsearch.script.ExecutableScript)24 CompiledScript (org.elasticsearch.script.CompiledScript)15 HashMap (java.util.HashMap)9 Script (org.elasticsearch.script.Script)9 Map (java.util.Map)8 BytesReference (org.elasticsearch.common.bytes.BytesReference)7 Mustache (com.github.mustachejava.Mustache)4 ArrayList (java.util.ArrayList)4 XContentParser (org.elasticsearch.common.xcontent.XContentParser)4 IOException (java.io.IOException)3 ScriptEngineService (org.elasticsearch.script.ScriptEngineService)3 SearchScript (org.elasticsearch.script.SearchScript)3 List (java.util.List)2 IndexReader (org.apache.lucene.index.IndexReader)2 MapperService (org.elasticsearch.index.mapper.MapperService)2 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)2 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Collections.unmodifiableMap (java.util.Collections.unmodifiableMap)1