Search in sources :

Example 41 with DeleteRequest

use of org.elasticsearch.action.delete.DeleteRequest in project elasticsearch by elastic.

the class DeleteDocumentationIT method testDelete.

/**
     * This test documents docs/java-rest/high-level/document/delete.asciidoc
     */
public void testDelete() throws IOException {
    RestHighLevelClient client = highLevelClient();
    // tag::delete-request[]
    DeleteRequest request = new DeleteRequest(// <1>
    "index", // <2>
    "type", // <3>
    "id");
    // end::delete-request[]
    // tag::delete-request-props[]
    // <1>
    request.timeout(TimeValue.timeValueSeconds(1));
    // <2>
    request.timeout("1s");
    // <3>
    request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
    // <4>
    request.setRefreshPolicy("wait_for");
    // <5>
    request.version(2);
    // <6>
    request.versionType(VersionType.EXTERNAL);
    // end::delete-request-props[]
    // tag::delete-execute[]
    DeleteResponse response = client.delete(request);
    try {
        // tag::delete-notfound[]
        if (response.getResult().equals(DocWriteResponse.Result.NOT_FOUND)) {
            // <1>
            throw new Exception("Can't find document to be removed");
        }
    // end::delete-notfound[]
    } catch (Exception ignored) {
    }
    // tag::delete-execute-async[]
    client.deleteAsync(request, new ActionListener<DeleteResponse>() {

        @Override
        public void onResponse(DeleteResponse deleteResponse) {
        // <1>
        }

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    });
    // tag::delete-conflict[]
    try {
        client.delete(request);
    } catch (ElasticsearchException exception) {
        if (exception.status().equals(RestStatus.CONFLICT)) {
        // <1>
        }
    }
// end::delete-conflict[]
}
Also used : DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) ElasticsearchException(org.elasticsearch.ElasticsearchException) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) ElasticsearchException(org.elasticsearch.ElasticsearchException) IOException(java.io.IOException)

Example 42 with DeleteRequest

use of org.elasticsearch.action.delete.DeleteRequest in project elasticsearch by elastic.

the class RequestTests method testDelete.

public void testDelete() throws IOException {
    String index = randomAsciiOfLengthBetween(3, 10);
    String type = randomAsciiOfLengthBetween(3, 10);
    String id = randomAsciiOfLengthBetween(3, 10);
    DeleteRequest deleteRequest = new DeleteRequest(index, type, id);
    Map<String, String> expectedParams = new HashMap<>();
    setRandomTimeout(deleteRequest, expectedParams);
    setRandomRefreshPolicy(deleteRequest, expectedParams);
    setRandomVersion(deleteRequest, expectedParams);
    setRandomVersionType(deleteRequest, expectedParams);
    if (frequently()) {
        if (randomBoolean()) {
            String routing = randomAsciiOfLengthBetween(3, 10);
            deleteRequest.routing(routing);
            expectedParams.put("routing", routing);
        }
        if (randomBoolean()) {
            String parent = randomAsciiOfLengthBetween(3, 10);
            deleteRequest.parent(parent);
            expectedParams.put("parent", parent);
        }
    }
    Request request = Request.delete(deleteRequest);
    assertEquals("/" + index + "/" + type + "/" + id, request.endpoint);
    assertEquals(expectedParams, request.params);
    assertEquals("DELETE", request.method);
    assertNull(request.entity);
}
Also used : HashMap(java.util.HashMap) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) WriteRequest(org.elasticsearch.action.support.WriteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) BulkShardRequest(org.elasticsearch.action.bulk.BulkShardRequest) GetRequest(org.elasticsearch.action.get.GetRequest) ReplicatedWriteRequest(org.elasticsearch.action.support.replication.ReplicatedWriteRequest) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) DocWriteRequest(org.elasticsearch.action.DocWriteRequest) ReplicationRequest(org.elasticsearch.action.support.replication.ReplicationRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest)

Example 43 with DeleteRequest

use of org.elasticsearch.action.delete.DeleteRequest in project elasticsearch by elastic.

the class IndicesRequestIT method testDelete.

public void testDelete() {
    String[] deleteShardActions = new String[] { BulkAction.NAME + "[s][p]", BulkAction.NAME + "[s][r]" };
    interceptTransportActions(deleteShardActions);
    DeleteRequest deleteRequest = new DeleteRequest(randomIndexOrAlias(), "type", "id");
    internalCluster().coordOnlyNodeClient().delete(deleteRequest).actionGet();
    clearInterceptedActions();
    assertSameIndices(deleteRequest, deleteShardActions);
}
Also used : DeleteRequest(org.elasticsearch.action.delete.DeleteRequest)

Example 44 with DeleteRequest

use of org.elasticsearch.action.delete.DeleteRequest in project elasticsearch by elastic.

the class IndicesRequestIT method testBulk.

public void testBulk() {
    String[] bulkShardActions = new String[] { BulkAction.NAME + "[s][p]", BulkAction.NAME + "[s][r]" };
    interceptTransportActions(bulkShardActions);
    List<String> indices = new ArrayList<>();
    BulkRequest bulkRequest = new BulkRequest();
    int numIndexRequests = iterations(1, 10);
    for (int i = 0; i < numIndexRequests; i++) {
        String indexOrAlias = randomIndexOrAlias();
        bulkRequest.add(new IndexRequest(indexOrAlias, "type", "id").source(Requests.INDEX_CONTENT_TYPE, "field", "value"));
        indices.add(indexOrAlias);
    }
    int numDeleteRequests = iterations(1, 10);
    for (int i = 0; i < numDeleteRequests; i++) {
        String indexOrAlias = randomIndexOrAlias();
        bulkRequest.add(new DeleteRequest(indexOrAlias, "type", "id"));
        indices.add(indexOrAlias);
    }
    int numUpdateRequests = iterations(1, 10);
    for (int i = 0; i < numUpdateRequests; i++) {
        String indexOrAlias = randomIndexOrAlias();
        bulkRequest.add(new UpdateRequest(indexOrAlias, "type", "id").doc(Requests.INDEX_CONTENT_TYPE, "field1", "value1"));
        indices.add(indexOrAlias);
    }
    internalCluster().coordOnlyNodeClient().bulk(bulkRequest).actionGet();
    clearInterceptedActions();
    assertIndicesSubset(indices, bulkShardActions);
}
Also used : UpdateRequest(org.elasticsearch.action.update.UpdateRequest) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ArrayList(java.util.ArrayList) IndexRequest(org.elasticsearch.action.index.IndexRequest) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) CloseIndexRequest(org.elasticsearch.action.admin.indices.close.CloseIndexRequest) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest)

Example 45 with DeleteRequest

use of org.elasticsearch.action.delete.DeleteRequest in project titan by thinkaurelius.

the class ElasticSearchIndex method mutate.

@Override
public void mutate(Map<String, Map<String, IndexMutation>> mutations, KeyInformation.IndexRetriever informations, BaseTransaction tx) throws BackendException {
    BulkRequestBuilder brb = client.prepareBulk();
    int bulkrequests = 0;
    try {
        for (Map.Entry<String, Map<String, IndexMutation>> stores : mutations.entrySet()) {
            String storename = stores.getKey();
            for (Map.Entry<String, IndexMutation> entry : stores.getValue().entrySet()) {
                String docid = entry.getKey();
                IndexMutation mutation = entry.getValue();
                assert mutation.isConsolidated();
                Preconditions.checkArgument(!(mutation.isNew() && mutation.isDeleted()));
                Preconditions.checkArgument(!mutation.isNew() || !mutation.hasDeletions());
                Preconditions.checkArgument(!mutation.isDeleted() || !mutation.hasAdditions());
                //Deletions first
                if (mutation.hasDeletions()) {
                    if (mutation.isDeleted()) {
                        log.trace("Deleting entire document {}", docid);
                        brb.add(new DeleteRequest(indexName, storename, docid));
                    } else {
                        String script = getDeletionScript(informations, storename, mutation);
                        brb.add(client.prepareUpdate(indexName, storename, docid).setScript(script, ScriptService.ScriptType.INLINE));
                        log.trace("Adding script {}", script);
                    }
                    bulkrequests++;
                }
                if (mutation.hasAdditions()) {
                    int ttl = mutation.determineTTL();
                    if (mutation.isNew()) {
                        //Index
                        log.trace("Adding entire document {}", docid);
                        brb.add(new IndexRequest(indexName, storename, docid).source(getNewDocument(mutation.getAdditions(), informations.get(storename), ttl)));
                    } else {
                        Preconditions.checkArgument(ttl == 0, "Elasticsearch only supports TTL on new documents [%s]", docid);
                        boolean needUpsert = !mutation.hasDeletions();
                        String script = getAdditionScript(informations, storename, mutation);
                        UpdateRequestBuilder update = client.prepareUpdate(indexName, storename, docid).setScript(script, ScriptService.ScriptType.INLINE);
                        if (needUpsert) {
                            XContentBuilder doc = getNewDocument(mutation.getAdditions(), informations.get(storename), ttl);
                            update.setUpsert(doc);
                        }
                        brb.add(update);
                        log.trace("Adding script {}", script);
                    }
                    bulkrequests++;
                }
            }
        }
        if (bulkrequests > 0) {
            BulkResponse bulkItemResponses = brb.execute().actionGet();
            if (bulkItemResponses.hasFailures()) {
                boolean actualFailure = false;
                for (BulkItemResponse response : bulkItemResponses.getItems()) {
                    //The document may have been deleted, which is OK
                    if (response.isFailed() && response.getFailure().getStatus() != RestStatus.NOT_FOUND) {
                        log.error("Failed to execute ES query {}", response.getFailureMessage());
                        actualFailure = true;
                    }
                }
                if (actualFailure) {
                    throw new Exception(bulkItemResponses.buildFailureMessage());
                }
            }
        }
    } catch (Exception e) {
        log.error("Failed to execute ES query {}", brb.request().timeout(), e);
        throw convert(e);
    }
}
Also used : UpdateRequestBuilder(org.elasticsearch.action.update.UpdateRequestBuilder) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) IndexRequest(org.elasticsearch.action.index.IndexRequest) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) FileNotFoundException(java.io.FileNotFoundException) TitanException(com.thinkaurelius.titan.core.TitanException) IndexMissingException(org.elasticsearch.indices.IndexMissingException) IOException(java.io.IOException) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Aggregations

DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)57 IndexRequest (org.elasticsearch.action.index.IndexRequest)35 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)24 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)16 IOException (java.io.IOException)15 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)11 DeleteResponse (org.elasticsearch.action.delete.DeleteResponse)11 Map (java.util.Map)9 HashMap (java.util.HashMap)8 ElasticsearchException (org.elasticsearch.ElasticsearchException)7 DeleteIndexRequest (org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 BulkItemResponse (org.elasticsearch.action.bulk.BulkItemResponse)6 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)6 BulkResponse (org.elasticsearch.action.bulk.BulkResponse)6 GetRequest (org.elasticsearch.action.get.GetRequest)5 SearchRequest (org.elasticsearch.action.search.SearchRequest)5 BytesReference (org.elasticsearch.common.bytes.BytesReference)5 XContentType (org.elasticsearch.common.xcontent.XContentType)5