Search in sources :

Example 1 with UpdateRequest

use of org.elasticsearch.action.update.UpdateRequest in project elasticsearch by elastic.

the class IndicesRequestIT method testUpdateUpsert.

public void testUpdateUpsert() {
    //update action goes to the primary, index op gets executed locally, then replicated
    String[] updateShardActions = new String[] { UpdateAction.NAME + "[s]", BulkAction.NAME + "[s][p]", BulkAction.NAME + "[s][r]" };
    interceptTransportActions(updateShardActions);
    String indexOrAlias = randomIndexOrAlias();
    UpdateRequest updateRequest = new UpdateRequest(indexOrAlias, "type", "id").upsert(Requests.INDEX_CONTENT_TYPE, "field", "value").doc(Requests.INDEX_CONTENT_TYPE, "field1", "value1");
    UpdateResponse updateResponse = internalCluster().coordOnlyNodeClient().update(updateRequest).actionGet();
    assertEquals(DocWriteResponse.Result.CREATED, updateResponse.getResult());
    clearInterceptedActions();
    assertSameIndices(updateRequest, updateShardActions);
}
Also used : UpdateResponse(org.elasticsearch.action.update.UpdateResponse) UpdateRequest(org.elasticsearch.action.update.UpdateRequest)

Example 2 with UpdateRequest

use of org.elasticsearch.action.update.UpdateRequest in project elasticsearch by elastic.

the class Request method bulk.

static Request bulk(BulkRequest bulkRequest) throws IOException {
    Params parameters = Params.builder();
    parameters.withTimeout(bulkRequest.timeout());
    parameters.withRefreshPolicy(bulkRequest.getRefreshPolicy());
    // Bulk API only supports newline delimited JSON or Smile. Before executing
    // the bulk, we need to check that all requests have the same content-type
    // and this content-type is supported by the Bulk API.
    XContentType bulkContentType = null;
    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> request = bulkRequest.requests().get(i);
        DocWriteRequest.OpType opType = request.opType();
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            bulkContentType = enforceSameContentType((IndexRequest) request, bulkContentType);
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) request;
            if (updateRequest.doc() != null) {
                bulkContentType = enforceSameContentType(updateRequest.doc(), bulkContentType);
            }
            if (updateRequest.upsertRequest() != null) {
                bulkContentType = enforceSameContentType(updateRequest.upsertRequest(), bulkContentType);
            }
        }
    }
    if (bulkContentType == null) {
        bulkContentType = XContentType.JSON;
    }
    byte separator = bulkContentType.xContent().streamSeparator();
    ContentType requestContentType = ContentType.create(bulkContentType.mediaType());
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    for (DocWriteRequest<?> request : bulkRequest.requests()) {
        DocWriteRequest.OpType opType = request.opType();
        try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) {
            metadata.startObject();
            {
                metadata.startObject(opType.getLowercase());
                if (Strings.hasLength(request.index())) {
                    metadata.field("_index", request.index());
                }
                if (Strings.hasLength(request.type())) {
                    metadata.field("_type", request.type());
                }
                if (Strings.hasLength(request.id())) {
                    metadata.field("_id", request.id());
                }
                if (Strings.hasLength(request.routing())) {
                    metadata.field("_routing", request.routing());
                }
                if (Strings.hasLength(request.parent())) {
                    metadata.field("_parent", request.parent());
                }
                if (request.version() != Versions.MATCH_ANY) {
                    metadata.field("_version", request.version());
                }
                VersionType versionType = request.versionType();
                if (versionType != VersionType.INTERNAL) {
                    if (versionType == VersionType.EXTERNAL) {
                        metadata.field("_version_type", "external");
                    } else if (versionType == VersionType.EXTERNAL_GTE) {
                        metadata.field("_version_type", "external_gte");
                    } else if (versionType == VersionType.FORCE) {
                        metadata.field("_version_type", "force");
                    }
                }
                if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
                    IndexRequest indexRequest = (IndexRequest) request;
                    if (Strings.hasLength(indexRequest.getPipeline())) {
                        metadata.field("pipeline", indexRequest.getPipeline());
                    }
                } else if (opType == DocWriteRequest.OpType.UPDATE) {
                    UpdateRequest updateRequest = (UpdateRequest) request;
                    if (updateRequest.retryOnConflict() > 0) {
                        metadata.field("_retry_on_conflict", updateRequest.retryOnConflict());
                    }
                    if (updateRequest.fetchSource() != null) {
                        metadata.field("_source", updateRequest.fetchSource());
                    }
                }
                metadata.endObject();
            }
            metadata.endObject();
            BytesRef metadataSource = metadata.bytes().toBytesRef();
            content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length);
            content.write(separator);
        }
        BytesRef source = null;
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest indexRequest = (IndexRequest) request;
            BytesReference indexSource = indexRequest.source();
            XContentType indexXContentType = indexRequest.getContentType();
            try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, indexSource, indexXContentType)) {
                try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) {
                    builder.copyCurrentStructure(parser);
                    source = builder.bytes().toBytesRef();
                }
            }
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            source = XContentHelper.toXContent((UpdateRequest) request, bulkContentType, false).toBytesRef();
        }
        if (source != null) {
            content.write(source.bytes, source.offset, source.length);
            content.write(separator);
        }
    }
    HttpEntity entity = new ByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType);
    return new Request(HttpPost.METHOD_NAME, "/_bulk", parameters.getParams(), entity);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) ContentType(org.apache.http.entity.ContentType) HttpEntity(org.apache.http.HttpEntity) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) WriteRequest(org.elasticsearch.action.support.WriteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) GetRequest(org.elasticsearch.action.get.GetRequest) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IndexRequest(org.elasticsearch.action.index.IndexRequest) VersionType(org.elasticsearch.index.VersionType) XContentType(org.elasticsearch.common.xcontent.XContentType) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) BytesRef(org.apache.lucene.util.BytesRef) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 3 with UpdateRequest

use of org.elasticsearch.action.update.UpdateRequest in project elasticsearch by elastic.

the class Request method update.

static Request update(UpdateRequest updateRequest) throws IOException {
    String endpoint = endpoint(updateRequest.index(), updateRequest.type(), updateRequest.id(), "_update");
    Params parameters = Params.builder();
    parameters.withRouting(updateRequest.routing());
    parameters.withParent(updateRequest.parent());
    parameters.withTimeout(updateRequest.timeout());
    parameters.withRefreshPolicy(updateRequest.getRefreshPolicy());
    parameters.withWaitForActiveShards(updateRequest.waitForActiveShards());
    parameters.withDocAsUpsert(updateRequest.docAsUpsert());
    parameters.withFetchSourceContext(updateRequest.fetchSource());
    parameters.withRetryOnConflict(updateRequest.retryOnConflict());
    parameters.withVersion(updateRequest.version());
    parameters.withVersionType(updateRequest.versionType());
    // The Java API allows update requests with different content types
    // set for the partial document and the upsert document. This client
    // only accepts update requests that have the same content types set
    // for both doc and upsert.
    XContentType xContentType = null;
    if (updateRequest.doc() != null) {
        xContentType = updateRequest.doc().getContentType();
    }
    if (updateRequest.upsertRequest() != null) {
        XContentType upsertContentType = updateRequest.upsertRequest().getContentType();
        if ((xContentType != null) && (xContentType != upsertContentType)) {
            throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType + "]" + " and upsert [" + upsertContentType + "] documents");
        } else {
            xContentType = upsertContentType;
        }
    }
    if (xContentType == null) {
        xContentType = Requests.INDEX_CONTENT_TYPE;
    }
    BytesRef source = XContentHelper.toXContent(updateRequest, xContentType, false).toBytesRef();
    HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, ContentType.create(xContentType.mediaType()));
    return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), entity);
}
Also used : XContentType(org.elasticsearch.common.xcontent.XContentType) HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) WriteRequest(org.elasticsearch.action.support.WriteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) GetRequest(org.elasticsearch.action.get.GetRequest) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BytesRef(org.apache.lucene.util.BytesRef)

Example 4 with UpdateRequest

use of org.elasticsearch.action.update.UpdateRequest in project elasticsearch by elastic.

the class BulkRequest method add.

public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType, @Nullable String defaultRouting, @Nullable String[] defaultFields, @Nullable FetchSourceContext defaultFetchSourceContext, @Nullable String defaultPipeline, @Nullable Object payload, boolean allowExplicitIndex, XContentType xContentType) throws IOException {
    XContent xContent = xContentType.xContent();
    int line = 0;
    int from = 0;
    int length = data.length();
    byte marker = xContent.streamSeparator();
    while (true) {
        int nextMarker = findNextMarker(marker, from, data, length);
        if (nextMarker == -1) {
            break;
        }
        line++;
        // EMPTY is safe here because we never call namedObject
        try (XContentParser parser = xContent.createParser(NamedXContentRegistry.EMPTY, data.slice(from, nextMarker - from))) {
            // move pointers
            from = nextMarker + 1;
            // Move to START_OBJECT
            XContentParser.Token token = parser.nextToken();
            if (token == null) {
                continue;
            }
            assert token == XContentParser.Token.START_OBJECT;
            // Move to FIELD_NAME, that's the action
            token = parser.nextToken();
            assert token == XContentParser.Token.FIELD_NAME;
            String action = parser.currentName();
            String index = defaultIndex;
            String type = defaultType;
            String id = null;
            String routing = defaultRouting;
            String parent = null;
            FetchSourceContext fetchSourceContext = defaultFetchSourceContext;
            String[] fields = defaultFields;
            String opType = null;
            long version = Versions.MATCH_ANY;
            VersionType versionType = VersionType.INTERNAL;
            int retryOnConflict = 0;
            String pipeline = defaultPipeline;
            // at this stage, next token can either be END_OBJECT (and use default index and type, with auto generated id)
            // or START_OBJECT which will have another set of parameters
            token = parser.nextToken();
            if (token == XContentParser.Token.START_OBJECT) {
                String currentFieldName = null;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else if (token.isValue()) {
                        if ("_index".equals(currentFieldName)) {
                            if (!allowExplicitIndex) {
                                throw new IllegalArgumentException("explicit index in bulk is not allowed");
                            }
                            index = parser.text();
                        } else if ("_type".equals(currentFieldName)) {
                            type = parser.text();
                        } else if ("_id".equals(currentFieldName)) {
                            id = parser.text();
                        } else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) {
                            routing = parser.text();
                        } else if ("_parent".equals(currentFieldName) || "parent".equals(currentFieldName)) {
                            parent = parser.text();
                        } else if ("op_type".equals(currentFieldName) || "opType".equals(currentFieldName)) {
                            opType = parser.text();
                        } else if ("_version".equals(currentFieldName) || "version".equals(currentFieldName)) {
                            version = parser.longValue();
                        } else if ("_version_type".equals(currentFieldName) || "_versionType".equals(currentFieldName) || "version_type".equals(currentFieldName) || "versionType".equals(currentFieldName)) {
                            versionType = VersionType.fromString(parser.text());
                        } else if ("_retry_on_conflict".equals(currentFieldName) || "_retryOnConflict".equals(currentFieldName)) {
                            retryOnConflict = parser.intValue();
                        } else if ("pipeline".equals(currentFieldName)) {
                            pipeline = parser.text();
                        } else if ("fields".equals(currentFieldName)) {
                            throw new IllegalArgumentException("Action/metadata line [" + line + "] contains a simple value for parameter [fields] while a list is expected");
                        } else if ("_source".equals(currentFieldName)) {
                            fetchSourceContext = FetchSourceContext.fromXContent(parser);
                        } else {
                            throw new IllegalArgumentException("Action/metadata line [" + line + "] contains an unknown parameter [" + currentFieldName + "]");
                        }
                    } else if (token == XContentParser.Token.START_ARRAY) {
                        if ("fields".equals(currentFieldName)) {
                            DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead");
                            List<Object> values = parser.list();
                            fields = values.toArray(new String[values.size()]);
                        } else {
                            throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected a simple value for field [" + currentFieldName + "] but found [" + token + "]");
                        }
                    } else if (token == XContentParser.Token.START_OBJECT && "_source".equals(currentFieldName)) {
                        fetchSourceContext = FetchSourceContext.fromXContent(parser);
                    } else if (token != XContentParser.Token.VALUE_NULL) {
                        throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected a simple value for field [" + currentFieldName + "] but found [" + token + "]");
                    }
                }
            } else if (token != XContentParser.Token.END_OBJECT) {
                throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected " + XContentParser.Token.START_OBJECT + " or " + XContentParser.Token.END_OBJECT + " but found [" + token + "]");
            }
            if ("delete".equals(action)) {
                add(new DeleteRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType), payload);
            } else {
                nextMarker = findNextMarker(marker, from, data, length);
                if (nextMarker == -1) {
                    break;
                }
                line++;
                // of index request.
                if ("index".equals(action)) {
                    if (opType == null) {
                        internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType).setPipeline(pipeline).source(sliceTrimmingCarriageReturn(data, from, nextMarker, xContentType), xContentType), payload);
                    } else {
                        internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType).create("create".equals(opType)).setPipeline(pipeline).source(sliceTrimmingCarriageReturn(data, from, nextMarker, xContentType), xContentType), payload);
                    }
                } else if ("create".equals(action)) {
                    internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType).create(true).setPipeline(pipeline).source(sliceTrimmingCarriageReturn(data, from, nextMarker, xContentType), xContentType), payload);
                } else if ("update".equals(action)) {
                    UpdateRequest updateRequest = new UpdateRequest(index, type, id).routing(routing).parent(parent).retryOnConflict(retryOnConflict).version(version).versionType(versionType).routing(routing).parent(parent);
                    // EMPTY is safe here because we never call namedObject
                    try (XContentParser sliceParser = xContent.createParser(NamedXContentRegistry.EMPTY, sliceTrimmingCarriageReturn(data, from, nextMarker, xContentType))) {
                        updateRequest.fromXContent(sliceParser);
                    }
                    if (fetchSourceContext != null) {
                        updateRequest.fetchSource(fetchSourceContext);
                    }
                    if (fields != null) {
                        updateRequest.fields(fields);
                    }
                    IndexRequest upsertRequest = updateRequest.upsertRequest();
                    if (upsertRequest != null) {
                        upsertRequest.version(version);
                        upsertRequest.versionType(versionType);
                    }
                    IndexRequest doc = updateRequest.doc();
                    if (doc != null) {
                        doc.version(version);
                        doc.versionType(versionType);
                    }
                    internalAdd(updateRequest, payload);
                }
                // move pointers
                from = nextMarker + 1;
            }
        }
    }
    return this;
}
Also used : UpdateRequest(org.elasticsearch.action.update.UpdateRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) VersionType(org.elasticsearch.index.VersionType) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) XContent(org.elasticsearch.common.xcontent.XContent) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 5 with UpdateRequest

use of org.elasticsearch.action.update.UpdateRequest in project elasticsearch by elastic.

the class RestUpdateAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    UpdateRequest updateRequest = new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(request.param("parent"));
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.setRefreshPolicy(request.param("refresh"));
    String waitForActiveShards = request.param("wait_for_active_shards");
    if (waitForActiveShards != null) {
        updateRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
    String sField = request.param("fields");
    if (sField != null && fetchSourceContext != null) {
        throw new IllegalArgumentException("[fields] and [_source] cannot be used in the same request");
    }
    if (sField != null) {
        DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead");
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        updateRequest.fields(sFields);
    } else if (fetchSourceContext != null) {
        updateRequest.fetchSource(fetchSourceContext);
    }
    updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));
    request.applyContentParser(parser -> {
        updateRequest.fromXContent(parser);
        IndexRequest upsertRequest = updateRequest.upsertRequest();
        if (upsertRequest != null) {
            upsertRequest.routing(request.param("routing"));
            upsertRequest.parent(request.param("parent"));
            upsertRequest.version(RestActions.parseVersion(request));
            upsertRequest.versionType(VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
        }
        IndexRequest doc = updateRequest.doc();
        if (doc != null) {
            doc.routing(request.param("routing"));
            doc.parent(request.param("parent"));
            doc.version(RestActions.parseVersion(request));
            doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
        }
    });
    return channel -> client.update(updateRequest, new RestStatusToXContentListener<>(channel, r -> r.getLocation(updateRequest.routing())));
}
Also used : Loggers(org.elasticsearch.common.logging.Loggers) BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) DeprecationLogger(org.elasticsearch.common.logging.DeprecationLogger) RestStatusToXContentListener(org.elasticsearch.rest.action.RestStatusToXContentListener) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) IOException(java.io.IOException) RestController(org.elasticsearch.rest.RestController) VersionType(org.elasticsearch.index.VersionType) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) POST(org.elasticsearch.rest.RestRequest.Method.POST) IndexRequest(org.elasticsearch.action.index.IndexRequest) Settings(org.elasticsearch.common.settings.Settings) RestRequest(org.elasticsearch.rest.RestRequest) NodeClient(org.elasticsearch.client.node.NodeClient) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest)

Aggregations

UpdateRequest (org.elasticsearch.action.update.UpdateRequest)59 IndexRequest (org.elasticsearch.action.index.IndexRequest)33 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)26 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)15 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)12 UpdateResponse (org.elasticsearch.action.update.UpdateResponse)9 HashMap (java.util.HashMap)8 GetRequest (org.elasticsearch.action.get.GetRequest)8 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 Script (org.elasticsearch.script.Script)6 ElasticsearchException (org.elasticsearch.ElasticsearchException)5 BulkItemResponse (org.elasticsearch.action.bulk.BulkItemResponse)5 WriteRequest (org.elasticsearch.action.support.WriteRequest)5 BytesReference (org.elasticsearch.common.bytes.BytesReference)5 TimeValue (org.elasticsearch.common.unit.TimeValue)5 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)5 XContentType (org.elasticsearch.common.xcontent.XContentType)5 VersionType (org.elasticsearch.index.VersionType)5 HttpEntity (org.apache.http.HttpEntity)4