Package org.elasticsearch.script

Examples of org.elasticsearch.script.ExecutableScript


                documents.add(document);

                ctx.put("documents", documents);
                try {
                    ExecutableScript executableScript = scriptService.executable(definition.getScriptType(), definition.getScript(),
                            ScriptService.ScriptType.INLINE, ImmutableMap.of("logger", logger));
                    if (logger.isTraceEnabled()) {
                        logger.trace("Script to be executed: {} - {}", definition.getScriptType(), definition.getScript());
                        logger.trace("Context before script executed: {}", ctx);
                    }
                    executableScript.setNextVar("ctx", ctx);
                    executableScript.run();
                    // we need to unwrap the context object...
                    ctx = (Map<String, Object>) executableScript.unwrap(ctx);
                } catch (Exception e) {
                    logger.error("failed to script process {}, ignoring", e, ctx);
                    MongoDBRiverHelper.setRiverStatus(esClient, definition.getRiverName(), Status.SCRIPT_IMPORT_FAILED);
                }
                if (logger.isTraceEnabled()) {
View Full Code Here


        @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(language, script, scriptType, parameters);
                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 ElasticsearchIllegalArgumentException("failed to execute script", e);
            }
        }
View Full Code Here

        boolean requestAdded = false;
        SearchRequestBuilder req;
        for (Correction correction : corrections) {
            spare.copyUTF8Bytes(correction.join(SEPARATOR, byteSpare, null, null));
            vars.put(SUGGESTION_TEMPLATE_VAR_NAME, spare.toString());
            ExecutableScript executable = scriptService.executable(collateScript, vars);
            BytesReference querySource = (BytesReference) executable.run();
            requestAdded = true;
            if (isFilter) {
                req = client.prepareSearch()
                        .setPreference(suggestions.getPreference())
                        .setQuery(QueryBuilders.constantScoreQuery(FilterBuilders.bytesFilter(querySource)))
View Full Code Here

        SearchContext.removeCurrent();
    }

    private void parseTemplate(ShardSearchRequest request) {

        final ExecutableScript executable;
        if (hasLength(request.templateName())) {
            executable = this.scriptService.executable("mustache", request.templateName(), request.templateType(), request.templateParams());
        } else {
            if (!hasLength(request.templateSource())) {
                return;
            }
            XContentParser parser = null;
            TemplateQueryParser.TemplateContext templateContext = null;

            try {
                parser = XContentFactory.xContent(request.templateSource()).createParser(request.templateSource());
                templateContext = TemplateQueryParser.parse(parser, "params", "template");

                if (templateContext.scriptType().equals(ScriptService.ScriptType.INLINE)) {
                    //Try to double parse for nested template id/file
                    parser = null;
                    try {
                        byte[] templateBytes = templateContext.template().getBytes(Charsets.UTF_8);
                        parser = XContentFactory.xContent(templateBytes).createParser(templateBytes);
                    } catch (ElasticsearchParseException epe) {
                        //This was an non-nested template, the parse failure was due to this, it is safe to assume this refers to a file
                        //for backwards compatibility and keep going
                        templateContext = new TemplateQueryParser.TemplateContext(ScriptService.ScriptType.FILE, templateContext.template(), templateContext.params());
                    }
                    if (parser != null) {
                        TemplateQueryParser.TemplateContext innerContext = TemplateQueryParser.parse(parser, "params");
                        if (hasLength(innerContext.template()) && !innerContext.scriptType().equals(ScriptService.ScriptType.INLINE)) {
                            //An inner template referring to a filename or id
                            templateContext = new TemplateQueryParser.TemplateContext(innerContext.scriptType(), innerContext.template(), templateContext.params());
                        }
                    }
                }
            } catch (IOException e) {
                throw new ElasticsearchParseException("Failed to parse template", e);
            } finally {
                Releasables.closeWhileHandlingException(parser);
            }

            if (templateContext == null || !hasLength(templateContext.template())) {
                throw new ElasticsearchParseException("Template must have [template] field configured");
            }
            executable = this.scriptService.executable("mustache", templateContext.template(), templateContext.scriptType(), templateContext.params());
        }

        BytesReference processedQuery = (BytesReference) executable.run();
        request.source(processedQuery);
    }
View Full Code Here

                params = new HashMap<String, Object>(firstAggregation.reduceParams);
            } else {
                params = new HashMap<String, Object>();
            }
            params.put("_aggs", aggregationObjects);
            ExecutableScript script = reduceContext.scriptService().executable(firstAggregation.scriptLang, firstAggregation.reduceScript,
                    firstAggregation.scriptType, params);
            aggregation = script.run();
        } else {
            aggregation = aggregationObjects;
        }
        return new InternalScriptedMetric(firstAggregation.getName(), aggregation, firstAggregation.scriptLang, firstAggregation.scriptType,
                firstAggregation.reduceScript, firstAggregation.reduceParams, getMetaData());
View Full Code Here

                Map<String, Object> ctx = new HashMap<>(2);
                // Tell the script that this is a create and not an update
                ctx.put("op", "create");
                ctx.put("_source", upsertDoc);
                try {
                    ExecutableScript script = scriptService.executable(request.scriptLang, request.script, request.scriptType, request.scriptParams);
                    script.setNextVar("ctx", ctx);
                    script.run();
                    // we need to unwrap the ctx...
                    ctx = (Map<String, Object>) script.unwrap(ctx);
                } catch (Exception e) {
                    throw new ElasticsearchIllegalArgumentException("failed to execute script", e);
                }               
                //Allow the script to set TTL using ctx._ttl
                ttl = getTTLFromScriptContext(ctx);
                //Allow the script to abort the create by setting "op" to "none"
                String scriptOpChoice = (String) ctx.get("op");
               
                // Only valid options for an upsert script are "create"
                // (the default) or "none", meaning abort upsert
                if (!"create".equals(scriptOpChoice)) {
                    if (!"none".equals(scriptOpChoice)) {
                        logger.warn("Used upsert operation [{}] for script [{}], doing nothing...", scriptOpChoice, request.script);
                    }
                    UpdateResponse update = new UpdateResponse(getResult.getIndex(), getResult.getType(), getResult.getId(),
                            getResult.getVersion(), false);
                    update.setGetResult(getResult);
                    return new Result(update, Operation.NONE, upsertDoc, XContentType.JSON);
                }
                indexRequest.source((Map)ctx.get("_source"));
            }

            indexRequest.index(request.index()).type(request.type()).id(request.id())
                    // it has to be a "create!"
                    .create(true)                   
                    .routing(request.routing())
                    .ttl(ttl)
                    .refresh(request.refresh())
                    .replicationType(request.replicationType()).consistencyLevel(request.consistencyLevel());
            indexRequest.operationThreaded(false);
            if (request.versionType() != VersionType.INTERNAL) {
                // in all but the internal versioning mode, we want to create the new document using the given version.
                indexRequest.version(request.version()).versionType(request.versionType());
            }
            return new Result(indexRequest, Operation.UPSERT, null, null);
        }

        long updateVersion = getResult.getVersion();

        if (request.versionType() != VersionType.INTERNAL) {
            assert request.versionType() == VersionType.FORCE;
            updateVersion = request.version(); // remember, match_any is excluded by the conflict test
        }

        if (getResult.internalSourceRef() == null) {
            // no source, we can't do nothing, through a failure...
            throw new DocumentSourceMissingException(new ShardId(indexShard.indexService().index().name(), request.shardId()), request.type(), request.id());
        }

        Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true);
        String operation = null;
        String timestamp;
        Long ttl = null;
        final Map<String, Object> updatedSourceAsMap;
        final XContentType updateSourceContentType = sourceAndContent.v1();
        String routing = getResult.getFields().containsKey(RoutingFieldMapper.NAME) ? getResult.field(RoutingFieldMapper.NAME).getValue().toString() : null;
        String parent = getResult.getFields().containsKey(ParentFieldMapper.NAME) ? getResult.field(ParentFieldMapper.NAME).getValue().toString() : null;

        if (request.script() == null && request.doc() != null) {
            IndexRequest indexRequest = request.doc();
            updatedSourceAsMap = sourceAndContent.v2();
            if (indexRequest.ttl() > 0) {
                ttl = indexRequest.ttl();
            }
            timestamp = indexRequest.timestamp();
            if (indexRequest.routing() != null) {
                routing = indexRequest.routing();
            }
            if (indexRequest.parent() != null) {
                parent = indexRequest.parent();
            }
            boolean noop = !XContentHelper.update(updatedSourceAsMap, indexRequest.sourceAsMap(), request.detectNoop());
            // noop could still be true even if detectNoop isn't because update detects empty maps as noops.  BUT we can only
            // actually turn the update into a noop if detectNoop is true to preserve backwards compatibility and to handle
            // cases where users repopulating multi-fields or adding synonyms, etc.
            if (request.detectNoop() && noop) {
                operation = "none";
            }
        } else {
            Map<String, Object> ctx = new HashMap<>(2);
            ctx.put("_source", sourceAndContent.v2());

            try {
                ExecutableScript script = scriptService.executable(request.scriptLang, request.script, request.scriptType, request.scriptParams);
                script.setNextVar("ctx", ctx);
                script.run();
                // we need to unwrap the ctx...
                ctx = (Map<String, Object>) script.unwrap(ctx);
            } catch (Exception e) {
                throw new ElasticsearchIllegalArgumentException("failed to execute script", e);
            }

            operation = (String) ctx.get("op");
View Full Code Here

    @Override
    @Nullable
    public Query parse(QueryParseContext parseContext) throws IOException {
        XContentParser parser = parseContext.parser();
        TemplateContext templateContext = parse(parser, PARAMS, parametersToTypes);
        ExecutableScript executable = this.scriptService.executable("mustache", templateContext.template(), templateContext.scriptType(), templateContext.params());

        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);
            Query result = context.parseInnerQuery();
View Full Code Here

TOP

Related Classes of org.elasticsearch.script.ExecutableScript

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.