Search in sources :

Example 6 with UpdateResponse

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

the class UpdateIT method testIndexAutoCreation.

public void testIndexAutoCreation() throws Exception {
    UpdateResponse updateResponse = client().prepareUpdate("test", "type1", "1").setUpsert(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject()).setScript(new Script(ScriptType.INLINE, "put_values", "", Collections.singletonMap("extra", "foo"))).setFetchSource(true).execute().actionGet();
    assertThat(updateResponse.getIndex(), equalTo("test"));
    assertThat(updateResponse.getGetResult(), notNullValue());
    assertThat(updateResponse.getGetResult().getIndex(), equalTo("test"));
    assertThat(updateResponse.getGetResult().sourceAsMap().get("bar").toString(), equalTo("baz"));
    assertThat(updateResponse.getGetResult().sourceAsMap().get("extra"), nullValue());
}
Also used : UpdateResponse(org.elasticsearch.action.update.UpdateResponse) SearchScript(org.elasticsearch.script.SearchScript) Script(org.elasticsearch.script.Script) CompiledScript(org.elasticsearch.script.CompiledScript) ExecutableScript(org.elasticsearch.script.ExecutableScript)

Example 7 with UpdateResponse

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

the class UpdateNoopIT method update.

private UpdateResponse update(Boolean detectNoop, long expectedVersion, XContentBuilder xContentBuilder) {
    UpdateRequestBuilder updateRequest = client().prepareUpdate("test", "type1", "1").setDoc(xContentBuilder).setDocAsUpsert(true).setFields("_source");
    if (detectNoop != null) {
        updateRequest.setDetectNoop(detectNoop);
    }
    UpdateResponse updateResponse = updateRequest.get();
    assertThat(updateResponse.getGetResult(), notNullValue());
    assertEquals(expectedVersion, updateResponse.getVersion());
    return updateResponse;
}
Also used : UpdateResponse(org.elasticsearch.action.update.UpdateResponse) UpdateRequestBuilder(org.elasticsearch.action.update.UpdateRequestBuilder)

Example 8 with UpdateResponse

use of org.elasticsearch.action.update.UpdateResponse in project jena by apache.

the class TextIndexES method addEntity.

/**
     * Add an Entity to the ElasticSearch Index.
     * The entity will be added as a new document in ES, if it does not already exists.
     * If the Entity exists, then the entity will simply be updated.
     * The entity will never be replaced.
     * @param entity the entity to add
     */
@Override
public void addEntity(Entity entity) {
    LOGGER.debug("Adding/Updating the entity in ES");
    //The field that has a not null value in the current Entity instance.
    //Required, mainly for building a script for the update command.
    String fieldToAdd = null;
    String fieldValueToAdd = null;
    try {
        XContentBuilder builder = jsonBuilder().startObject();
        for (String field : docDef.fields()) {
            if (entity.get(field) != null) {
                if (entity.getLanguage() != null && !entity.getLanguage().isEmpty()) {
                    //We make sure that the field name contains all underscore and no dash (for eg. when the lang value is en-GB)
                    //The reason to do this is because the script fails with exception in case we have "-" in field name.
                    fieldToAdd = normalizeFieldName(field, entity.getLanguage());
                } else {
                    fieldToAdd = field;
                }
                fieldValueToAdd = (String) entity.get(field);
                builder = builder.field(fieldToAdd, Arrays.asList(fieldValueToAdd));
                break;
            } else {
                //We are making sure that the field is at-least added to the index.
                //This will help us tremendously when we are appending the data later in an already indexed document.
                builder = builder.field(field, Collections.emptyList());
            }
        }
        builder = builder.endObject();
        IndexRequest indexRequest = new IndexRequest(indexName, docDef.getEntityField(), entity.getId()).source(builder);
        String addUpdateScript = ADD_UPDATE_SCRIPT.replaceAll("<fieldName>", fieldToAdd);
        Map<String, Object> params = new HashMap<>();
        params.put("fieldValue", fieldValueToAdd);
        UpdateRequest upReq = new UpdateRequest(indexName, docDef.getEntityField(), entity.getId()).script(new Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG, addUpdateScript, params)).upsert(indexRequest);
        UpdateResponse response = client.update(upReq).get();
        LOGGER.debug("Received the following Update response : " + response + " for the following entity: " + entity);
    } catch (Exception e) {
        throw new TextIndexException("Unable to Index the Entity in ElasticSearch.", e);
    }
}
Also used : Script(org.elasticsearch.script.Script) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException)

Example 9 with UpdateResponse

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

the class TransportShardBulkAction method executeUpdateRequest.

/**
     * Executes update request, delegating to a index or delete operation after translation,
     * handles retries on version conflict and constructs update response
     * NOTE: reassigns bulk item request at <code>requestIndex</code> for replicas to
     * execute translated update request (NOOP update is an exception). NOOP updates are
     * indicated by returning a <code>null</code> operation in {@link BulkItemResultHolder}
     * */
private static BulkItemResultHolder executeUpdateRequest(UpdateRequest updateRequest, IndexShard primary, IndexMetaData metaData, BulkShardRequest request, int requestIndex, UpdateHelper updateHelper, LongSupplier nowInMillis, final MappingUpdatePerformer mappingUpdater) throws Exception {
    Engine.Result updateOperationResult = null;
    UpdateResponse updateResponse = null;
    BulkItemRequest replicaRequest = request.items()[requestIndex];
    int maxAttempts = updateRequest.retryOnConflict();
    for (int attemptCount = 0; attemptCount <= maxAttempts; attemptCount++) {
        final UpdateHelper.Result translate;
        // translate update request
        try {
            translate = updateHelper.prepare(updateRequest, primary, nowInMillis);
        } catch (Exception failure) {
            // we may fail translating a update to index or delete operation
            // we use index result to communicate failure while translating update request
            updateOperationResult = new Engine.IndexResult(failure, updateRequest.version(), SequenceNumbersService.UNASSIGNED_SEQ_NO);
            // out of retry loop
            break;
        }
        // execute translated update request
        switch(translate.getResponseResult()) {
            case CREATED:
            case UPDATED:
                IndexRequest indexRequest = translate.action();
                MappingMetaData mappingMd = metaData.mappingOrDefault(indexRequest.type());
                indexRequest.process(mappingMd, request.index());
                updateOperationResult = executeIndexRequestOnPrimary(indexRequest, primary, mappingUpdater);
                break;
            case DELETED:
                DeleteRequest deleteRequest = translate.action();
                updateOperationResult = executeDeleteRequestOnPrimary(deleteRequest, primary);
                break;
            case NOOP:
                primary.noopUpdate(updateRequest.type());
                break;
            default:
                throw new IllegalStateException("Illegal update operation " + translate.getResponseResult());
        }
        if (updateOperationResult == null) {
            // this is a noop operation
            updateResponse = translate.action();
            // out of retry loop
            break;
        } else if (updateOperationResult.hasFailure() == false) {
            // set translated update (index/delete) request for replica execution in bulk items
            switch(updateOperationResult.getOperationType()) {
                case INDEX:
                    IndexRequest updateIndexRequest = translate.action();
                    final IndexResponse indexResponse = new IndexResponse(primary.shardId(), updateIndexRequest.type(), updateIndexRequest.id(), updateOperationResult.getSeqNo(), updateOperationResult.getVersion(), ((Engine.IndexResult) updateOperationResult).isCreated());
                    BytesReference indexSourceAsBytes = updateIndexRequest.source();
                    updateResponse = new UpdateResponse(indexResponse.getShardInfo(), indexResponse.getShardId(), indexResponse.getType(), indexResponse.getId(), indexResponse.getSeqNo(), indexResponse.getVersion(), indexResponse.getResult());
                    if ((updateRequest.fetchSource() != null && updateRequest.fetchSource().fetchSource()) || (updateRequest.fields() != null && updateRequest.fields().length > 0)) {
                        Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(indexSourceAsBytes, true, updateIndexRequest.getContentType());
                        updateResponse.setGetResult(updateHelper.extractGetResult(updateRequest, request.index(), indexResponse.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), indexSourceAsBytes));
                    }
                    // set translated request as replica request
                    replicaRequest = new BulkItemRequest(request.items()[requestIndex].id(), updateIndexRequest);
                    break;
                case DELETE:
                    DeleteRequest updateDeleteRequest = translate.action();
                    DeleteResponse deleteResponse = new DeleteResponse(primary.shardId(), updateDeleteRequest.type(), updateDeleteRequest.id(), updateOperationResult.getSeqNo(), updateOperationResult.getVersion(), ((Engine.DeleteResult) updateOperationResult).isFound());
                    updateResponse = new UpdateResponse(deleteResponse.getShardInfo(), deleteResponse.getShardId(), deleteResponse.getType(), deleteResponse.getId(), deleteResponse.getSeqNo(), deleteResponse.getVersion(), deleteResponse.getResult());
                    updateResponse.setGetResult(updateHelper.extractGetResult(updateRequest, request.index(), deleteResponse.getVersion(), translate.updatedSourceAsMap(), translate.updateSourceContentType(), null));
                    // set translated request as replica request
                    replicaRequest = new BulkItemRequest(request.items()[requestIndex].id(), updateDeleteRequest);
                    break;
            }
            assert updateOperationResult.getSeqNo() != SequenceNumbersService.UNASSIGNED_SEQ_NO;
            // out of retry loop
            break;
        } else if (updateOperationResult.getFailure() instanceof VersionConflictEngineException == false) {
            // out of retry loop
            break;
        }
    }
    return new BulkItemResultHolder(updateResponse, updateOperationResult, replicaRequest);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) IndexRequest(org.elasticsearch.action.index.IndexRequest) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) IOException(java.io.IOException) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) UpdateHelper(org.elasticsearch.action.update.UpdateHelper) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) IndexResponse(org.elasticsearch.action.index.IndexResponse) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) Engine(org.elasticsearch.index.engine.Engine) Tuple(org.elasticsearch.common.collect.Tuple)

Example 10 with UpdateResponse

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

the class BulkItemResponse method readFrom.

@Override
public void readFrom(StreamInput in) throws IOException {
    id = in.readVInt();
    if (in.getVersion().onOrAfter(Version.V_5_3_0_UNRELEASED)) {
        opType = OpType.fromId(in.readByte());
    } else {
        opType = OpType.fromString(in.readString());
    }
    byte type = in.readByte();
    if (type == 0) {
        response = new IndexResponse();
        response.readFrom(in);
    } else if (type == 1) {
        response = new DeleteResponse();
        response.readFrom(in);
    } else if (type == 3) {
        // make 3 instead of 2, because 2 is already in use for 'no responses'
        response = new UpdateResponse();
        response.readFrom(in);
    }
    if (in.readBoolean()) {
        failure = new Failure(in);
    }
}
Also used : UpdateResponse(org.elasticsearch.action.update.UpdateResponse) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse)

Aggregations

UpdateResponse (org.elasticsearch.action.update.UpdateResponse)23 Script (org.elasticsearch.script.Script)10 ExecutableScript (org.elasticsearch.script.ExecutableScript)8 CompiledScript (org.elasticsearch.script.CompiledScript)7 SearchScript (org.elasticsearch.script.SearchScript)7 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)6 GetResponse (org.elasticsearch.action.get.GetResponse)5 HashMap (java.util.HashMap)4 IndexRequest (org.elasticsearch.action.index.IndexRequest)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 Map (java.util.Map)3 DeleteResponse (org.elasticsearch.action.delete.DeleteResponse)3 IndexResponse (org.elasticsearch.action.index.IndexResponse)3 DocumentMissingException (org.elasticsearch.index.engine.DocumentMissingException)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)2 DocWriteResponse (org.elasticsearch.action.DocWriteResponse)2 Alias (org.elasticsearch.action.admin.indices.alias.Alias)2 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)2