org.elasticsearch.action.ActionWriteResponse Java Examples

The following examples show how to use org.elasticsearch.action.ActionWriteResponse. 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: TransportBroadcastReplicationAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private void finishAndNotifyListener(ActionListener listener, CopyOnWriteArrayList<ShardResponse> shardsResponses) {
    logger.trace("{}: got all shard responses", actionName);
    int successfulShards = 0;
    int failedShards = 0;
    int totalNumCopies = 0;
    List<ShardOperationFailedException> shardFailures = null;
    for (int i = 0; i < shardsResponses.size(); i++) {
        ActionWriteResponse shardResponse = shardsResponses.get(i);
        if (shardResponse == null) {
            // non active shard, ignore
        } else {
            failedShards += shardResponse.getShardInfo().getFailed();
            successfulShards += shardResponse.getShardInfo().getSuccessful();
            totalNumCopies += shardResponse.getShardInfo().getTotal();
            if (shardFailures == null) {
                shardFailures = new ArrayList<>();
            }
            for (ActionWriteResponse.ShardInfo.Failure failure : shardResponse.getShardInfo().getFailures()) {
                shardFailures.add(new DefaultShardOperationFailedException(new BroadcastShardOperationFailedException(new ShardId(failure.index(), failure.shardId()), failure.getCause())));
            }
        }
    }
    listener.onResponse(newResponse(successfulShards, failedShards, totalNumCopies, shardFailures));
}
 
Example #2
Source File: RestDeleteAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    DeleteRequest deleteRequest = new DeleteRequest(request.param("index"), request.param("type"), request.param("id"));
    deleteRequest.routing(request.param("routing"));
    deleteRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
    deleteRequest.timeout(request.paramAsTime("timeout", DeleteRequest.DEFAULT_TIMEOUT));
    deleteRequest.refresh(request.paramAsBoolean("refresh", deleteRequest.refresh()));
    deleteRequest.version(RestActions.parseVersion(request));
    deleteRequest.versionType(VersionType.fromString(request.param("version_type"), deleteRequest.versionType()));

    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        deleteRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }

    client.delete(deleteRequest, new RestBuilderListener<DeleteResponse>(channel) {
        @Override
        public RestResponse buildResponse(DeleteResponse result, XContentBuilder builder) throws Exception {
            ActionWriteResponse.ShardInfo shardInfo = result.getShardInfo();
            builder.startObject().field(Fields.FOUND, result.isFound())
                    .field(Fields._INDEX, result.getIndex())
                    .field(Fields._TYPE, result.getType())
                    .field(Fields._ID, result.getId())
                    .field(Fields._VERSION, result.getVersion())
                    .value(shardInfo)
                    .endObject();
            RestStatus status = shardInfo.status();
            if (!result.isFound()) {
                status = NOT_FOUND;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example #3
Source File: TransportShardFlushAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected Tuple<ActionWriteResponse, ShardFlushRequest> shardOperationOnPrimary(MetaData metaData, ShardFlushRequest shardRequest) throws Throwable {
    IndexShard indexShard = indicesService.indexServiceSafe(shardRequest.shardId().getIndex()).shardSafe(shardRequest.shardId().id());
    indexShard.flush(shardRequest.getRequest());
    logger.trace("{} flush request executed on primary", indexShard.shardId());
    return new Tuple<>(new ActionWriteResponse(), shardRequest);
}
 
Example #4
Source File: TransportShardRefreshAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected Tuple<ActionWriteResponse, ReplicationRequest> shardOperationOnPrimary(MetaData metaData, ReplicationRequest shardRequest) throws Throwable {
    IndexShard indexShard = indicesService.indexServiceSafe(shardRequest.shardId().getIndex()).shardSafe(shardRequest.shardId().id());
    indexShard.refresh("api");
    logger.trace("{} refresh request executed on primary", indexShard.shardId());
    return new Tuple<>(new ActionWriteResponse(), shardRequest);
}
 
Example #5
Source File: TransportReplicationAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T extends ActionWriteResponse> T response() {
    // this sets total, pending and failed to 0 and this is ok, because we will embed this into the replica
    // request and not use it
    response.setShardInfo(new ActionWriteResponse.ShardInfo());
    return (T) response;
}
 
Example #6
Source File: TransportReplicationAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void doFinish() {
    if (finished.compareAndSet(false, true)) {
        setPhase(task, "finished");
        Releasables.close(indexShardReference);
        final ActionWriteResponse.ShardInfo.Failure[] failuresArray;
        if (!shardReplicaFailures.isEmpty()) {
            int slot = 0;
            failuresArray = new ActionWriteResponse.ShardInfo.Failure[shardReplicaFailures.size()];
            for (Map.Entry<String, Throwable> entry : shardReplicaFailures.entrySet()) {
                RestStatus restStatus = ExceptionsHelper.status(entry.getValue());
                failuresArray[slot++] = new ActionWriteResponse.ShardInfo.Failure(
                    shardId.getIndex(), shardId.getId(), entry.getKey(), entry.getValue(), restStatus, false
                );
            }
        } else {
            failuresArray = ActionWriteResponse.EMPTY;
        }
        finalResponse.setShardInfo(new ActionWriteResponse.ShardInfo(
                totalShards,
                success.get(),
                failuresArray

            )
        );
        try {
            channel.sendResponse(finalResponse);
        } catch (IOException responseException) {
            logger.warn("failed to send error message back to client for action [" + transportReplicaAction + "]", responseException);
        }
        if (logger.isTraceEnabled()) {
            logger.trace("action [{}] completed on all replicas [{}] for request [{}]", transportReplicaAction, shardId, replicaRequest);
        }
    }
}
 
Example #7
Source File: RestUpdateAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    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.refresh(request.paramAsBoolean("refresh", updateRequest.refresh()));
    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        updateRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
    scriptParameterParser.parseParams(request);
    ScriptParameterValue scriptValue = scriptParameterParser.getDefaultScriptParameterValue();
    if (scriptValue != null) {
        Map<String, Object> scriptParams = new HashMap<>();
        for (Map.Entry<String, String> entry : request.params().entrySet()) {
            if (entry.getKey().startsWith("sp_")) {
                scriptParams.put(entry.getKey().substring(3), entry.getValue());
            }
        }
        updateRequest.script(new Script(scriptValue.script(), scriptValue.scriptType(), scriptParameterParser.lang(), scriptParams));
    }
    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            updateRequest.fields(sFields);
        }
    }
    updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));


    // see if we have it in the body
    if (request.hasContent()) {
        updateRequest.source(request.content());
        IndexRequest upsertRequest = updateRequest.upsertRequest();
        if (upsertRequest != null) {
            upsertRequest.routing(request.param("routing"));
            upsertRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            upsertRequest.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                upsertRequest.ttl(request.param("ttl"));
            }
            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")); // order is important, set it after routing, so it will set the routing
            doc.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                doc.ttl(request.param("ttl"));
            }
            doc.version(RestActions.parseVersion(request));
            doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
        }
    }

    client.update(updateRequest, new RestBuilderListener<UpdateResponse>(channel) {
        @Override
        public RestResponse buildResponse(UpdateResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            ActionWriteResponse.ShardInfo shardInfo = response.getShardInfo();
            builder.field(Fields._INDEX, response.getIndex())
                    .field(Fields._TYPE, response.getType())
                    .field(Fields._ID, response.getId())
                    .field(Fields._VERSION, response.getVersion());

            shardInfo.toXContent(builder, request);
            if (response.getGetResult() != null) {
                builder.startObject(Fields.GET);
                response.getGetResult().toXContentEmbedded(builder, request);
                builder.endObject();
            }

            builder.endObject();
            RestStatus status = shardInfo.status();
            if (response.isCreated()) {
                status = CREATED;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example #8
Source File: RestBulkAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    BulkRequest bulkRequest = Requests.bulkRequest();
    String defaultIndex = request.param("index");
    String defaultType = request.param("type");
    String defaultRouting = request.param("routing");
    String fieldsParam = request.param("fields");
    String[] defaultFields = fieldsParam != null ? Strings.commaDelimitedListToStringArray(fieldsParam) : null;

    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        bulkRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    bulkRequest.timeout(request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT));
    bulkRequest.refresh(request.paramAsBoolean("refresh", bulkRequest.refresh()));
    bulkRequest.add(request.content(), defaultIndex, defaultType, defaultRouting, defaultFields, null, allowExplicitIndex);

    client.bulk(bulkRequest, new RestBuilderListener<BulkResponse>(channel) {
        @Override
        public RestResponse buildResponse(BulkResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            builder.field(Fields.TOOK, response.getTookInMillis());
            builder.field(Fields.ERRORS, response.hasFailures());
            builder.startArray(Fields.ITEMS);
            for (BulkItemResponse itemResponse : response) {
                builder.startObject();
                builder.startObject(itemResponse.getOpType());
                builder.field(Fields._INDEX, itemResponse.getIndex());
                builder.field(Fields._TYPE, itemResponse.getType());
                builder.field(Fields._ID, itemResponse.getId());
                long version = itemResponse.getVersion();
                if (version != -1) {
                    builder.field(Fields._VERSION, itemResponse.getVersion());
                }
                if (itemResponse.isFailed()) {
                    builder.field(Fields.STATUS, itemResponse.getFailure().getStatus().getStatus());
                    builder.startObject(Fields.ERROR);
                    ElasticsearchException.toXContent(builder, request, itemResponse.getFailure().getCause());
                    builder.endObject();
                } else {
                    ActionWriteResponse.ShardInfo shardInfo = itemResponse.getResponse().getShardInfo();
                    shardInfo.toXContent(builder, request);
                    if (itemResponse.getResponse() instanceof DeleteResponse) {
                        DeleteResponse deleteResponse = itemResponse.getResponse();
                        if (deleteResponse.isFound()) {
                            builder.field(Fields.STATUS, shardInfo.status().getStatus());
                        } else {
                            builder.field(Fields.STATUS, RestStatus.NOT_FOUND.getStatus());
                        }
                        builder.field(Fields.FOUND, deleteResponse.isFound());
                    } else if (itemResponse.getResponse() instanceof IndexResponse) {
                        IndexResponse indexResponse = itemResponse.getResponse();
                        if (indexResponse.isCreated()) {
                            builder.field(Fields.STATUS, RestStatus.CREATED.getStatus());
                        } else {
                            builder.field(Fields.STATUS, shardInfo.status().getStatus());
                        }
                    } else if (itemResponse.getResponse() instanceof UpdateResponse) {
                        UpdateResponse updateResponse = itemResponse.getResponse();
                        if (updateResponse.isCreated()) {
                            builder.field(Fields.STATUS, RestStatus.CREATED.getStatus());
                        } else {
                            builder.field(Fields.STATUS, shardInfo.status().getStatus());
                        }
                        if (updateResponse.getGetResult() != null) {
                            builder.startObject(Fields.GET);
                            updateResponse.getGetResult().toXContentEmbedded(builder, request);
                            builder.endObject();
                        }
                    }
                }
                builder.endObject();
                builder.endObject();
            }
            builder.endArray();

            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example #9
Source File: TransportFlushAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected ActionWriteResponse newShardResponse() {
    return new ActionWriteResponse();
}
 
Example #10
Source File: TransportShardFlushAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected ActionWriteResponse newResponseInstance() {
    return new ActionWriteResponse();
}
 
Example #11
Source File: TransportShardRefreshAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected ActionWriteResponse newResponseInstance() {
    return new ActionWriteResponse();
}
 
Example #12
Source File: TransportRefreshAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected ActionWriteResponse newShardResponse() {
    return new ActionWriteResponse();
}
 
Example #13
Source File: BulkItemResponse.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public BulkItemResponse(int id, String opType, ActionWriteResponse response) {
    this.id = id;
    this.opType = opType;
    this.response = response;
}
 
Example #14
Source File: BulkItemResponse.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * The actual response ({@link IndexResponse} or {@link DeleteResponse}). <tt>null</tt> in
 * case of failure.
 */
public <T extends ActionWriteResponse> T getResponse() {
    return (T) response;
}
 
Example #15
Source File: DcBulkItemResponseImpl.java    From io with Apache License 2.0 2 votes vote down vote up
/**
 * .
 * @param id .
 * @param opType .
 * @param response .
 */
public DcBulkItemResponseImpl(int id, String opType, ActionWriteResponse response) {
    super(id, opType, response);
}