Search in sources :

Example 11 with BulkRequest

use of org.elasticsearch.action.bulk.BulkRequest in project elasticsearch by elastic.

the class ParentTaskAssigningClientTests method testSetsParentId.

public void testSetsParentId() {
    TaskId[] parentTaskId = new TaskId[] { new TaskId(randomAsciiOfLength(3), randomLong()) };
    // This mock will do nothing but verify that parentTaskId is set on all requests sent to it.
    NoOpClient mock = new NoOpClient(getTestName()) {

        @Override
        protected <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
            assertEquals(parentTaskId[0], request.getParentTask());
            super.doExecute(action, request, listener);
        }
    };
    try (ParentTaskAssigningClient client = new ParentTaskAssigningClient(mock, parentTaskId[0])) {
        // All of these should have the parentTaskId set
        client.bulk(new BulkRequest());
        client.search(new SearchRequest());
        client.clearScroll(new ClearScrollRequest());
        // Now lets verify that unwrapped calls don't have the parentTaskId set
        parentTaskId[0] = TaskId.EMPTY_TASK_ID;
        client.unwrap().bulk(new BulkRequest());
        client.unwrap().search(new SearchRequest());
        client.unwrap().clearScroll(new ClearScrollRequest());
    }
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) Action(org.elasticsearch.action.Action) TaskId(org.elasticsearch.tasks.TaskId) ActionRequest(org.elasticsearch.action.ActionRequest) ClearScrollRequest(org.elasticsearch.action.search.ClearScrollRequest) SearchRequest(org.elasticsearch.action.search.SearchRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ActionResponse(org.elasticsearch.action.ActionResponse) ActionRequestBuilder(org.elasticsearch.action.ActionRequestBuilder) ActionListener(org.elasticsearch.action.ActionListener) ActionRequest(org.elasticsearch.action.ActionRequest) NoOpClient(org.elasticsearch.test.client.NoOpClient) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ClearScrollRequest(org.elasticsearch.action.search.ClearScrollRequest)

Example 12 with BulkRequest

use of org.elasticsearch.action.bulk.BulkRequest in project samza by apache.

the class ElasticsearchSystemProducer method register.

@Override
public void register(final String source) {
    BulkProcessor.Listener listener = new BulkProcessor.Listener() {

        @Override
        public void beforeBulk(long executionId, BulkRequest request) {
        // Nothing to do.
        }

        @Override
        public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
            boolean hasFatalError = false;
            //Do not consider version conficts to be errors. Ignore old versions
            if (response.hasFailures()) {
                for (BulkItemResponse itemResp : response.getItems()) {
                    if (itemResp.isFailed()) {
                        if (itemResp.getFailure().getStatus().equals(RestStatus.CONFLICT)) {
                            LOGGER.info("Failed to index document in Elasticsearch: " + itemResp.getFailureMessage());
                        } else {
                            hasFatalError = true;
                            LOGGER.error("Failed to index document in Elasticsearch: " + itemResp.getFailureMessage());
                        }
                    }
                }
            }
            if (hasFatalError) {
                sendFailed.set(true);
            } else {
                updateSuccessMetrics(response);
            }
        }

        @Override
        public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
            LOGGER.error(failure.getMessage());
            thrown.compareAndSet(null, failure);
            sendFailed.set(true);
        }

        private void updateSuccessMetrics(BulkResponse response) {
            metrics.bulkSendSuccess.inc();
            int writes = 0;
            for (BulkItemResponse itemResp : response.getItems()) {
                if (itemResp.isFailed()) {
                    if (itemResp.getFailure().getStatus().equals(RestStatus.CONFLICT)) {
                        metrics.conflicts.inc();
                    }
                } else {
                    ActionResponse resp = itemResp.getResponse();
                    if (resp instanceof IndexResponse) {
                        writes += 1;
                        if (((IndexResponse) resp).isCreated()) {
                            metrics.inserts.inc();
                        } else {
                            metrics.updates.inc();
                        }
                    } else {
                        LOGGER.error("Unexpected Elasticsearch action response type: " + resp.getClass().getSimpleName());
                    }
                }
            }
            LOGGER.info(String.format("Wrote %s messages from %s to %s.", writes, source, system));
        }
    };
    sourceBulkProcessor.put(source, bulkProcessorFactory.getBulkProcessor(client, listener));
}
Also used : IndexResponse(org.elasticsearch.action.index.IndexResponse) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BulkProcessor(org.elasticsearch.action.bulk.BulkProcessor) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) ActionResponse(org.elasticsearch.action.ActionResponse)

Example 13 with BulkRequest

use of org.elasticsearch.action.bulk.BulkRequest in project elasticsearch by elastic.

the class RestBulkAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    BulkRequest bulkRequest = Requests.bulkRequest();
    String defaultIndex = request.param("index");
    String defaultType = request.param("type");
    String defaultRouting = request.param("routing");
    FetchSourceContext defaultFetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
    String fieldsParam = request.param("fields");
    if (fieldsParam != null) {
        DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead");
    }
    String[] defaultFields = fieldsParam != null ? Strings.commaDelimitedListToStringArray(fieldsParam) : null;
    String defaultPipeline = request.param("pipeline");
    String waitForActiveShards = request.param("wait_for_active_shards");
    if (waitForActiveShards != null) {
        bulkRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards));
    }
    bulkRequest.timeout(request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT));
    bulkRequest.setRefreshPolicy(request.param("refresh"));
    bulkRequest.add(request.content(), defaultIndex, defaultType, defaultRouting, defaultFields, defaultFetchSourceContext, defaultPipeline, null, allowExplicitIndex, request.getXContentType());
    return channel -> client.bulk(bulkRequest, new RestStatusToXContentListener<>(channel));
}
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) IOException(java.io.IOException) RestController(org.elasticsearch.rest.RestController) PUT(org.elasticsearch.rest.RestRequest.Method.PUT) Strings(org.elasticsearch.common.Strings) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) BulkShardRequest(org.elasticsearch.action.bulk.BulkShardRequest) RestRequest(org.elasticsearch.rest.RestRequest) NodeClient(org.elasticsearch.client.node.NodeClient) Requests(org.elasticsearch.client.Requests) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) BulkRequest(org.elasticsearch.action.bulk.BulkRequest)

Example 14 with BulkRequest

use of org.elasticsearch.action.bulk.BulkRequest in project elasticsearch by elastic.

the class RestNoopBulkAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    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 defaultPipeline = request.param("pipeline");
    String[] defaultFields = fieldsParam != null ? Strings.commaDelimitedListToStringArray(fieldsParam) : null;
    String waitForActiveShards = request.param("wait_for_active_shards");
    if (waitForActiveShards != null) {
        bulkRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards));
    }
    bulkRequest.timeout(request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT));
    bulkRequest.setRefreshPolicy(request.param("refresh"));
    bulkRequest.add(request.content(), defaultIndex, defaultType, defaultRouting, defaultFields, null, defaultPipeline, null, true, request.getXContentType());
    // short circuit the call to the transport layer
    return channel -> {
        BulkRestBuilderListener listener = new BulkRestBuilderListener(channel, request);
        listener.onResponse(bulkRequest);
    };
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) DocWriteResponse(org.elasticsearch.action.DocWriteResponse) PUT(org.elasticsearch.rest.RestRequest.Method.PUT) Strings(org.elasticsearch.common.Strings) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) RestChannel(org.elasticsearch.rest.RestChannel) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) BulkShardRequest(org.elasticsearch.action.bulk.BulkShardRequest) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) RestRequest(org.elasticsearch.rest.RestRequest) OK(org.elasticsearch.rest.RestStatus.OK) NodeClient(org.elasticsearch.client.node.NodeClient) Requests(org.elasticsearch.client.Requests) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest)

Example 15 with BulkRequest

use of org.elasticsearch.action.bulk.BulkRequest in project elasticsearch by elastic.

the class AsyncBulkByScrollActionTests method bulkRetryTestCase.

/**
     * Execute a bulk retry test case. The total number of failures is random and the number of retries attempted is set to
     * testRequest.getMaxRetries and controled by the failWithRejection parameter.
     */
private void bulkRetryTestCase(boolean failWithRejection) throws Exception {
    int totalFailures = randomIntBetween(1, testRequest.getMaxRetries());
    int size = randomIntBetween(1, 100);
    testRequest.setMaxRetries(totalFailures - (failWithRejection ? 1 : 0));
    client.bulksToReject = client.bulksAttempts.get() + totalFailures;
    /*
         * When we get a successful bulk response we usually start the next scroll request but lets just intercept that so we don't have to
         * deal with it. We just wait for it to happen.
         */
    CountDownLatch successLatch = new CountDownLatch(1);
    DummyAsyncBulkByScrollAction action = new DummyActionWithoutBackoff() {

        @Override
        void startNextScroll(TimeValue lastBatchStartTime, int lastBatchSize) {
            successLatch.countDown();
        }
    };
    BulkRequest request = new BulkRequest();
    for (int i = 0; i < size + 1; i++) {
        request.add(new IndexRequest("index", "type", "id" + i));
    }
    action.sendBulkRequest(timeValueNanos(System.nanoTime()), request);
    if (failWithRejection) {
        BulkByScrollResponse response = listener.get();
        assertThat(response.getBulkFailures(), hasSize(1));
        assertEquals(response.getBulkFailures().get(0).getStatus(), RestStatus.TOO_MANY_REQUESTS);
        assertThat(response.getSearchFailures(), empty());
        assertNull(response.getReasonCancelled());
    } else {
        assertTrue(successLatch.await(10, TimeUnit.SECONDS));
    }
}
Also used : BulkRequest(org.elasticsearch.action.bulk.BulkRequest) CountDownLatch(java.util.concurrent.CountDownLatch) IndexRequest(org.elasticsearch.action.index.IndexRequest) TimeValue(org.elasticsearch.common.unit.TimeValue)

Aggregations

BulkRequest (org.elasticsearch.action.bulk.BulkRequest)27 IndexRequest (org.elasticsearch.action.index.IndexRequest)18 BulkResponse (org.elasticsearch.action.bulk.BulkResponse)10 BulkItemResponse (org.elasticsearch.action.bulk.BulkItemResponse)9 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)7 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)7 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)5 ArrayList (java.util.ArrayList)4 ElasticsearchException (org.elasticsearch.ElasticsearchException)4 GetRequest (org.elasticsearch.action.get.GetRequest)4 BytesReference (org.elasticsearch.common.bytes.BytesReference)4 IOException (java.io.IOException)3 ActionRequest (org.elasticsearch.action.ActionRequest)3 DeleteIndexRequest (org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest)3 BulkShardRequest (org.elasticsearch.action.bulk.BulkShardRequest)3 SearchRequest (org.elasticsearch.action.search.SearchRequest)3 Settings (org.elasticsearch.common.settings.Settings)3 XContentType (org.elasticsearch.common.xcontent.XContentType)3 Test (org.junit.Test)3 List (java.util.List)2