org.elasticsearch.script.ScriptContext Java Examples

The following examples show how to use org.elasticsearch.script.ScriptContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ScriptedMetricAggregator.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
protected ScriptedMetricAggregator(String name, Script initScript, Script mapScript, Script combineScript, Script reduceScript,
        Map<String, Object> params, AggregationContext context, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData)
        throws IOException {
    super(name, context, parent, pipelineAggregators, metaData);
    this.params = params;
    ScriptService scriptService = context.searchContext().scriptService();
    if (initScript != null) {
        scriptService.executable(initScript, ScriptContext.Standard.AGGS, context.searchContext(), Collections.<String, String>emptyMap()).run();
    }
    this.mapScript = scriptService.search(context.searchContext().lookup(), mapScript, ScriptContext.Standard.AGGS, Collections.<String, String>emptyMap());
    if (combineScript != null) {
        this.combineScript = scriptService.executable(combineScript, ScriptContext.Standard.AGGS, context.searchContext(), Collections.<String, String>emptyMap());
    } else {
        this.combineScript = null;
    }
    this.reduceScript = reduceScript;
}
 
Example #2
Source File: TemplateQueryParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the template query replacing template parameters with provided
 * values. Handles both submitting the template as part of the request as
 * well as referencing only the template name.
 *
 * @param parseContext
 *            parse context containing the templated query.
 */
@Override
@Nullable
public Query parse(QueryParseContext parseContext) throws IOException {
    XContentParser parser = parseContext.parser();
    Template template = parse(parser, parseContext.parseFieldMatcher());
    ExecutableScript executable = this.scriptService.executable(template, ScriptContext.Standard.SEARCH, SearchContext.current(), Collections.<String, String>emptyMap());

    BytesReference querySource = (BytesReference) executable.run();

    try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) {
        final QueryParseContext context = new QueryParseContext(parseContext.index(), parseContext.indexQueryParserService());
        context.reset(qSourceParser);
        return context.parseInnerQuery();
    }
}
 
Example #3
Source File: DocumentMapper.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> transformSourceAsMap(Map<String, Object> sourceAsMap) {
    try {
        // We use the ctx variable and the _source name to be consistent with the update api.
        ExecutableScript executable = scriptService.executable(script, ScriptContext.Standard.MAPPING, null, Collections.<String, String>emptyMap());
        Map<String, Object> ctx = new HashMap<>(1);
        ctx.put("_source", sourceAsMap);
        executable.setNextVar("ctx", ctx);
        executable.run();
        ctx = (Map<String, Object>) executable.unwrap(ctx);
        return (Map<String, Object>) ctx.get("_source");
    } catch (Exception e) {
        throw new IllegalArgumentException("failed to execute script", e);
    }
}
 
Example #4
Source File: TransportRenderSearchTemplateAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute(final RenderSearchTemplateRequest request, final ActionListener<RenderSearchTemplateResponse> listener) {
    threadPool.generic().execute(new AbstractRunnable() {

        @Override
        public void onFailure(Throwable t) {
            listener.onFailure(t);
        }

        @Override
        protected void doRun() throws Exception {
            ExecutableScript executable = scriptService.executable(request.template(), ScriptContext.Standard.SEARCH, request, Collections.<String, String>emptyMap());
            BytesReference processedTemplate = (BytesReference) executable.run();
            RenderSearchTemplateResponse response = new RenderSearchTemplateResponse();
            response.source(processedTemplate);
            listener.onResponse(response);
        }
    });
}
 
Example #5
Source File: BucketSelectorPipelineAggregator.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@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, reduceContext, Collections.<String, String>emptyMap());
    List newBuckets = new ArrayList<>();
    for (Bucket bucket : buckets) {
        Map<String, Object> vars = new HashMap<>();
        if (script.getParams() != null) {
            vars.putAll(script.getParams());
        }
        for (Map.Entry<String, String> entry : bucketsPathsMap.entrySet()) {
            String varName = entry.getKey();
            String bucketsPath = entry.getValue();
            Double value = resolveBucketValue(originalAgg, bucket, bucketsPath, gapPolicy);
            vars.put(varName, value);
        }
        ExecutableScript executableScript = reduceContext.scriptService().executable(compiledScript, vars);
        Object scriptReturnValue = executableScript.run();
        final boolean keepBucket;
        // TODO: WTF!!!!!
        if ("expression".equals(script.getLang())) {
            double scriptDoubleValue = (double) scriptReturnValue;
            keepBucket = scriptDoubleValue == 1.0;
        } else {
            keepBucket = (boolean) scriptReturnValue;
        }
        if (keepBucket) {
            newBuckets.add(bucket);
        }
    }
    return originalAgg.create(newBuckets);
}
 
Example #6
Source File: ScriptHeuristic.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(InternalAggregation.ReduceContext context) {
    searchScript = context.scriptService().executable(script, ScriptContext.Standard.AGGS, context, Collections.<String, String>emptyMap());
    searchScript.setNextVar("_subset_freq", subsetDfHolder);
    searchScript.setNextVar("_subset_size", subsetSizeHolder);
    searchScript.setNextVar("_superset_freq", supersetDfHolder);
    searchScript.setNextVar("_superset_size", supersetSizeHolder);
}
 
Example #7
Source File: UpdateHelper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> executeScript(UpdateRequest request, Map<String, Object> ctx) {
    try {
        if (scriptService != null) {
            ExecutableScript script = scriptService.executable(request.script, ScriptContext.Standard.UPDATE, request, Collections.<String, String>emptyMap());
            script.setNextVar("ctx", ctx);
            script.run();
            // we need to unwrap the ctx...
            ctx = (Map<String, Object>) script.unwrap(ctx);
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("failed to execute script", e);
    }
    return ctx;
}
 
Example #8
Source File: RankLibScriptEngine.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params) {

    RankLibModelContainer.Factory retFactory = () -> {
        LtrRanker ltrRanker = factory.getParser(RanklibModelParser.TYPE).parse(null, scriptSource);
        return new RankLibModelContainer(ltrRanker);
    };

    return context.factoryClazz.cast(retFactory);
}
 
Example #9
Source File: ScriptGeoSimplify.java    From elasticsearch-plugin-geoshape with MIT License 5 votes vote down vote up
@Override
public <T> T compile(String scriptName, String scriptSource,
                     ScriptContext<T> context, Map<String, String> params) {
    if (!context.equals(FieldScript.CONTEXT)) {
        throw new IllegalArgumentException(getType()
                + " scripts cannot be used for context ["
                + context.name + "]");
    }
    if ("geo_simplify".equals(scriptName)) {
        FieldScript.Factory factory = GeoSearchLeafFactory::new;
        return context.factoryClazz.cast(factory);
    }
    throw new IllegalArgumentException("Unknown script name " + scriptSource);
}
 
Example #10
Source File: DynaRankWhitelistExtension.java    From elasticsearch-dynarank with Apache License 2.0 4 votes vote down vote up
@Override
public Map<ScriptContext<?>, List<Whitelist>> getContextWhitelists() {
    return Collections.singletonMap(DynaRankScript.CONTEXT, Collections.singletonList(WHITELIST));
}
 
Example #11
Source File: VectorScoringPlugin.java    From elasticsearch-vector-scoring with Apache License 2.0 4 votes vote down vote up
@Override
public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
    return new VectorScoreEngine();
}
 
Example #12
Source File: DynamicRankingPlugin.java    From elasticsearch-dynarank with Apache License 2.0 4 votes vote down vote up
@Override
public List<ScriptContext<?>> getContexts() {
    return Arrays.asList(DynaRankScript.CONTEXT);
}
 
Example #13
Source File: DynamicRankingPlugin.java    From elasticsearch-dynarank with Apache License 2.0 4 votes vote down vote up
@Override
public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
    return new DiversitySortScriptEngine(settings);
}
 
Example #14
Source File: DiversitySortScriptEngine.java    From elasticsearch-dynarank with Apache License 2.0 4 votes vote down vote up
@Override
public Set<ScriptContext<?>> getSupportedContexts() {
    return Collections.singleton(DynaRankScript.CONTEXT);
}
 
Example #15
Source File: DiversitySortScriptEngine.java    From elasticsearch-dynarank with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T compile(String name, String code, ScriptContext<T> context, Map<String, String> options) {
    DynaRankScript.Factory compiled = params -> new DiversitySortExecutableScript(params, bucketFactories);
    return context.factoryClazz.cast(compiled);
}
 
Example #16
Source File: GeoExtensionPlugin.java    From elasticsearch-plugin-geoshape with MIT License 4 votes vote down vote up
@Override
public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
    return new ScriptGeoSimplify();
}
 
Example #17
Source File: ScriptGeoSimplify.java    From elasticsearch-plugin-geoshape with MIT License 4 votes vote down vote up
@Override
public Set<ScriptContext<?>> getSupportedContexts() {
    return Collections.singleton(CONTEXT);
}
 
Example #18
Source File: RankLibScriptEngine.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
@Override
public Set<ScriptContext<?>> getSupportedContexts() {
    return Collections.singleton(RankLibScriptEngine.CONTEXT);
}
 
Example #19
Source File: LtrQueryParserPlugin.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
@Override
public List<ScriptContext<?>> getContexts() {
    ScriptContext<?> contexts = RankLibScriptEngine.CONTEXT;
    return Collections.singletonList(contexts);
}
 
Example #20
Source File: LtrQueryParserPlugin.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
@Override
public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
    return new RankLibScriptEngine(parserFactory);
}
 
Example #21
Source File: ScriptQueryParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ScriptQuery(Script script, ScriptService scriptService, SearchLookup searchLookup) {
    this.script = script;
    this.searchScript = scriptService.search(searchLookup, script, ScriptContext.Standard.SEARCH, Collections.<String, String>emptyMap());
}
 
Example #22
Source File: ValuesSourceParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private SearchScript createScript() {
    return input.script == null ? null : context.scriptService().search(context.lookup(), input.script, ScriptContext.Standard.AGGS, Collections.<String, String>emptyMap());
}
 
Example #23
Source File: BucketScriptPipelineAggregator.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@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, reduceContext, Collections.<String, String>emptyMap());
    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");
                }
                List<InternalAggregation> aggs = new ArrayList<>(eagerTransform(bucket.getAggregations().asList(), FUNCTION));
                aggs.add(new InternalSimpleValue(name(), ((Number) returned).doubleValue(), formatter,
                        new ArrayList<PipelineAggregator>(), metaData()));
                InternalMultiBucketAggregation.InternalBucket newBucket = originalAgg.createBucket(new InternalAggregations(aggs),
                        (InternalMultiBucketAggregation.InternalBucket) bucket);
                newBuckets.add(newBucket);
            }
        }
    }
    return originalAgg.create(newBuckets);
}