org.elasticsearch.script.ExecutableScript Java Examples

The following examples show how to use org.elasticsearch.script.ExecutableScript. 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: ScriptHeuristic.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public ScriptHeuristic(ExecutableScript searchScript, Script script) {
    subsetSizeHolder = new LongAccessor();
    supersetSizeHolder = new LongAccessor();
    subsetDfHolder = new LongAccessor();
    supersetDfHolder = new LongAccessor();
    this.searchScript = searchScript;
    if (searchScript != null) {
        searchScript.setNextVar("_subset_freq", subsetDfHolder);
        searchScript.setNextVar("_subset_size", subsetSizeHolder);
        searchScript.setNextVar("_superset_freq", supersetDfHolder);
        searchScript.setNextVar("_superset_size", supersetSizeHolder);
    }
    this.script = script;


}
 
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: IsPrimeSearchScriptFactory.java    From elasticsearch-native-script-example with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called for every search on every shard.
 *
 * @param params list of script parameters passed with the query
 * @return new native script
 */
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
    // Example of a mandatory string parameter
    // The XContentMapValues helper class can be used to simplify parameter parsing
    String fieldName = params == null ? null : XContentMapValues.nodeStringValue(params.get("field"), defaultFieldName);
    if (!Strings.hasLength(fieldName)) {
        throw new IllegalArgumentException("Missing the field parameter");
    }

    // Example of an optional integer  parameter
    int certainty = params == null ? 10 : XContentMapValues.nodeIntegerValue(params.get("certainty"), 10);
    return new IsPrimeSearchScript(fieldName, certainty);
}
 
Example #6
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 #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: InitScriptFactory.java    From elasticsearch-native-script-example with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public ExecutableScript newScript(final @Nullable Map<String, Object> params) {
    return new AbstractExecutableScript() {
        @Override
        public Object run() {
            ((Map<String, Object>)params.get("_agg")).put(TRANSACTIONS_FIELD, new ArrayList<>());
            return null;
        }
    };
}
 
Example #9
Source File: ContentAuthPluginScriptFactory.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ExecutableScript newScript(final Map<String, Object> params) {
  checkNotNull(params);
  String subjectId = (String) checkNotNull(params.get(SUBJECT_PARAM));
  Subject subject = ContentAuthPlugin.getSearchSubjectHelper().getSubject(subjectId);
  return new ContentAuthPluginScript(
      subject,
      ContentAuthPlugin.getContentPermissionChecker(),
      ContentAuthPlugin.getVariableResolverAdapterManager(),
      ContentAuthPlugin.getRepositoryManager(),
      ContentAuthPlugin.getContentAuthSleep());
}
 
Example #10
Source File: MustacheScriptEngineService.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public ExecutableScript executable(CompiledScript compiledScript,
        @Nullable Map<String, Object> vars) {
    return new MustacheExecutableScript(compiledScript, vars);
}
 
Example #11
Source File: ReduceScriptFactory.java    From elasticsearch-native-script-example with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public ExecutableScript newScript(final @Nullable Map<String, Object> params) {
    final ArrayList<Long> aggs = (ArrayList<Long>) params.get("_aggs");
    return new ReduceScript(aggs);
}
 
Example #12
Source File: CombineScriptFactory.java    From elasticsearch-native-script-example with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public ExecutableScript newScript(final @Nullable Map<String, Object> params) {
    Map<String, Object> agg = (Map<String, Object>) params.get("_agg");
    return new CombineScript(agg);
}
 
Example #13
Source File: MapScriptFactory.java    From elasticsearch-native-script-example with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public ExecutableScript newScript(final @Nullable Map<String, Object> params) {
    Map<String, Object> agg = (Map<String, Object>) params.get("_agg");
    return new MapScript(agg);
}
 
Example #14
Source File: VectorScoringScriptEngineService.java    From fast-elasticsearch-vector-scoring with Apache License 2.0 4 votes vote down vote up
@Override
public ExecutableScript executable(CompiledScript compiledScript, @Nullable Map<String, Object> vars) {
    VectorScoreScript.Factory scriptFactory = (VectorScoreScript.Factory) compiledScript.compiled();
    return scriptFactory.newScript(vars);
}
 
Example #15
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);
}
 
Example #16
Source File: FeatureVectorScoringSearchScript.java    From elasticsearch-feature-vector-scoring with Apache License 2.0 4 votes vote down vote up
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) throws ScriptException {
    return new FeatureVectorScoringSearchScript(params);
}
 
Example #17
Source File: PayloadVectorScoreScript.java    From elasticsearch-vector-scoring with Apache License 2.0 2 votes vote down vote up
/**
 * This method is called for every search on every shard.
 *
 * @param params
 *            list of script parameters passed with the query
 * @return new native script
 */
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
    return new PayloadVectorScoreScript(params);
}
 
Example #18
Source File: VectorScoreScript.java    From fast-elasticsearch-vector-scoring with Apache License 2.0 2 votes vote down vote up
/**
 * This method is called for every search on every shard.
 * 
 * @param params
 *            list of script parameters passed with the query
 * @return new native script
 */
public ExecutableScript newScript(@Nullable Map<String, Object> params) throws ScriptException {
    return new VectorScoreScript(params);
}