Search in sources :

Example 1 with LatchedActionListener

use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.

the class CRUDDocumentationIT method testUpdate.

@SuppressWarnings("unused")
public void testUpdate() throws Exception {
    RestHighLevelClient client = highLevelClient();
    {
        IndexRequest indexRequest = new IndexRequest("posts").id("1").source("field", 0);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        assertSame(RestStatus.CREATED, indexResponse.status());
        Request request = new Request("POST", "/_scripts/increment-field");
        request.setJsonEntity(Strings.toString(JsonXContent.contentBuilder().startObject().startObject("script").field("lang", "painless").field("source", "ctx._source.field += params.count").endObject().endObject()));
        Response response = client().performRequest(request);
        assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode());
    }
    {
        // tag::update-request
        UpdateRequest request = new UpdateRequest(// <1>
        "posts", // <2>
        "1");
        // end::update-request
        request.fetchSource(true);
        // tag::update-request-with-inline-script
        // <1>
        Map<String, Object> parameters = singletonMap("count", 4);
        Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.field += params.count", // <2>
        parameters);
        // <3>
        request.script(inline);
        // end::update-request-with-inline-script
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
        assertEquals(4, updateResponse.getGetResult().getSource().get("field"));
        request = new UpdateRequest("posts", "1").fetchSource(true);
        // tag::update-request-with-stored-script
        Script stored = new Script(ScriptType.STORED, null, "increment-field", // <1>
        parameters);
        // <2>
        request.script(stored);
        // end::update-request-with-stored-script
        updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
        assertEquals(8, updateResponse.getGetResult().getSource().get("field"));
    }
    {
        // tag::update-request-with-doc-as-map
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("updated", new Date());
        jsonMap.put("reason", "daily update");
        UpdateRequest request = new UpdateRequest("posts", "1").doc(// <1>
        jsonMap);
        // end::update-request-with-doc-as-map
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
    }
    {
        // tag::update-request-with-doc-as-xcontent
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.timeField("updated", new Date());
            builder.field("reason", "daily update");
        }
        builder.endObject();
        UpdateRequest request = new UpdateRequest("posts", "1").doc(// <1>
        builder);
        // end::update-request-with-doc-as-xcontent
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
    }
    {
        // tag::update-request-shortcut
        UpdateRequest request = new UpdateRequest("posts", "1").doc("updated", new Date(), "reason", // <1>
        "daily update");
        // end::update-request-shortcut
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
    }
    {
        // tag::update-request-with-doc-as-string
        UpdateRequest request = new UpdateRequest("posts", "1");
        String jsonString = "{" + "\"updated\":\"2017-01-01\"," + "\"reason\":\"daily update\"" + "}";
        // <1>
        request.doc(jsonString, XContentType.JSON);
        // end::update-request-with-doc-as-string
        request.fetchSource(true);
        // tag::update-execute
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        // end::update-execute
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
        // tag::update-response
        String index = updateResponse.getIndex();
        String id = updateResponse.getId();
        long version = updateResponse.getVersion();
        if (updateResponse.getResult() == DocWriteResponse.Result.CREATED) {
        // <1>
        } else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED) {
        // <2>
        } else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED) {
        // <3>
        } else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP) {
        // <4>
        }
        // end::update-response
        // tag::update-getresult
        // <1>
        GetResult result = updateResponse.getGetResult();
        if (result.isExists()) {
            // <2>
            String sourceAsString = result.sourceAsString();
            // <3>
            Map<String, Object> sourceAsMap = result.sourceAsMap();
            // <4>
            byte[] sourceAsBytes = result.source();
        } else {
        // <5>
        }
        // end::update-getresult
        assertNotNull(result);
        assertEquals(3, result.sourceAsMap().size());
        // tag::update-failure
        ReplicationResponse.ShardInfo shardInfo = updateResponse.getShardInfo();
        if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
        // <1>
        }
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                // <2>
                String reason = failure.reason();
            }
        }
    // end::update-failure
    }
    {
        // tag::update-docnotfound
        UpdateRequest request = new UpdateRequest("posts", "does_not_exist").doc("field", "value");
        try {
            UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        } catch (OpenSearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
            // <1>
            }
        }
    // end::update-docnotfound
    }
    {
        // tag::update-conflict
        UpdateRequest request = new UpdateRequest("posts", "1").doc("field", "value").setIfSeqNo(101L).setIfPrimaryTerm(200L);
        try {
            UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        } catch (OpenSearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
            // <1>
            }
        }
    // end::update-conflict
    }
    {
        UpdateRequest request = new UpdateRequest("posts", "1").doc("reason", "no source");
        // tag::update-request-no-source
        // <1>
        request.fetchSource(true);
        // end::update-request-no-source
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
        assertNotNull(updateResponse.getGetResult());
        assertEquals(3, updateResponse.getGetResult().sourceAsMap().size());
    }
    {
        UpdateRequest request = new UpdateRequest("posts", "1").doc("reason", "source includes");
        // tag::update-request-source-include
        String[] includes = new String[] { "updated", "r*" };
        String[] excludes = Strings.EMPTY_ARRAY;
        request.fetchSource(// <1>
        new FetchSourceContext(true, includes, excludes));
        // end::update-request-source-include
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
        Map<String, Object> sourceAsMap = updateResponse.getGetResult().sourceAsMap();
        assertEquals(2, sourceAsMap.size());
        assertEquals("source includes", sourceAsMap.get("reason"));
        assertTrue(sourceAsMap.containsKey("updated"));
    }
    {
        UpdateRequest request = new UpdateRequest("posts", "1").doc("reason", "source excludes");
        // tag::update-request-source-exclude
        String[] includes = Strings.EMPTY_ARRAY;
        String[] excludes = new String[] { "updated" };
        request.fetchSource(// <1>
        new FetchSourceContext(true, includes, excludes));
        // end::update-request-source-exclude
        UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
        assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult());
        Map<String, Object> sourceAsMap = updateResponse.getGetResult().sourceAsMap();
        assertEquals(2, sourceAsMap.size());
        assertEquals("source excludes", sourceAsMap.get("reason"));
        assertTrue(sourceAsMap.containsKey("field"));
    }
    {
        UpdateRequest request = new UpdateRequest("posts", "id");
        // tag::update-request-routing
        // <1>
        request.routing("routing");
        // end::update-request-routing
        // tag::update-request-timeout
        // <1>
        request.timeout(TimeValue.timeValueSeconds(1));
        // <2>
        request.timeout("1s");
        // end::update-request-timeout
        // tag::update-request-retry
        // <1>
        request.retryOnConflict(3);
        // end::update-request-retry
        // tag::update-request-refresh
        // <1>
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
        // <2>
        request.setRefreshPolicy("wait_for");
        // end::update-request-refresh
        // tag::update-request-cas
        // <1>
        request.setIfSeqNo(2L);
        // <2>
        request.setIfPrimaryTerm(1L);
        // end::update-request-cas
        // tag::update-request-detect-noop
        // <1>
        request.detectNoop(false);
        // end::update-request-detect-noop
        // tag::update-request-upsert
        String jsonString = "{\"created\":\"2017-01-01\"}";
        // <1>
        request.upsert(jsonString, XContentType.JSON);
        // end::update-request-upsert
        // tag::update-request-scripted-upsert
        // <1>
        request.scriptedUpsert(true);
        // end::update-request-scripted-upsert
        // tag::update-request-doc-upsert
        // <1>
        request.docAsUpsert(true);
        // end::update-request-doc-upsert
        // tag::update-request-active-shards
        // <1>
        request.waitForActiveShards(2);
        // <2>
        request.waitForActiveShards(ActiveShardCount.ALL);
    // end::update-request-active-shards
    }
    {
        UpdateRequest request = new UpdateRequest("posts", "async").doc("reason", "async update").docAsUpsert(true);
        ActionListener<UpdateResponse> listener;
        // tag::update-execute-listener
        listener = new ActionListener<UpdateResponse>() {

            @Override
            public void onResponse(UpdateResponse updateResponse) {
            // <1>
            }

            @Override
            public void onFailure(Exception e) {
            // <2>
            }
        };
        // end::update-execute-listener
        // Replace the empty listener by a blocking listener in test
        final CountDownLatch latch = new CountDownLatch(1);
        listener = new LatchedActionListener<>(listener, latch);
        // tag::update-execute-async
        // <1>
        client.updateAsync(request, RequestOptions.DEFAULT, listener);
        // end::update-execute-async
        assertTrue(latch.await(30L, TimeUnit.SECONDS));
    }
}
Also used : Script(org.opensearch.script.Script) GetResult(org.opensearch.index.get.GetResult) UpdateRequest(org.opensearch.action.update.UpdateRequest) BulkRequest(org.opensearch.action.bulk.BulkRequest) Request(org.opensearch.client.Request) WriteRequest(org.opensearch.action.support.WriteRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) UpdateRequest(org.opensearch.action.update.UpdateRequest) RethrottleRequest(org.opensearch.client.RethrottleRequest) GetSourceRequest(org.opensearch.client.core.GetSourceRequest) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) DocWriteRequest(org.opensearch.action.DocWriteRequest) GetRequest(org.opensearch.action.get.GetRequest) UpdateByQueryRequest(org.opensearch.index.reindex.UpdateByQueryRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) DeleteByQueryRequest(org.opensearch.index.reindex.DeleteByQueryRequest) IndexRequest(org.opensearch.action.index.IndexRequest) ReindexRequest(org.opensearch.index.reindex.ReindexRequest) MultiGetRequest(org.opensearch.action.get.MultiGetRequest) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) Matchers.containsString(org.hamcrest.Matchers.containsString) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) CountDownLatch(java.util.concurrent.CountDownLatch) Date(java.util.Date) OpenSearchException(org.opensearch.OpenSearchException) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) MultiGetResponse(org.opensearch.action.get.MultiGetResponse) IndexResponse(org.opensearch.action.index.IndexResponse) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) GetResponse(org.opensearch.action.get.GetResponse) MultiTermVectorsResponse(org.opensearch.client.core.MultiTermVectorsResponse) ReplicationResponse(org.opensearch.action.support.replication.ReplicationResponse) DocWriteResponse(org.opensearch.action.DocWriteResponse) Response(org.opensearch.client.Response) GetSourceResponse(org.opensearch.client.core.GetSourceResponse) UpdateResponse(org.opensearch.action.update.UpdateResponse) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) TermVectorsResponse(org.opensearch.client.core.TermVectorsResponse) DeleteResponse(org.opensearch.action.delete.DeleteResponse) CreateIndexResponse(org.opensearch.client.indices.CreateIndexResponse) BulkByScrollResponse(org.opensearch.index.reindex.BulkByScrollResponse) MultiGetItemResponse(org.opensearch.action.get.MultiGetItemResponse) BulkResponse(org.opensearch.action.bulk.BulkResponse) UpdateResponse(org.opensearch.action.update.UpdateResponse) LatchedActionListener(org.opensearch.action.LatchedActionListener) FetchSourceContext(org.opensearch.search.fetch.subphase.FetchSourceContext) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) IndexResponse(org.opensearch.action.index.IndexResponse) CreateIndexResponse(org.opensearch.client.indices.CreateIndexResponse) OpenSearchException(org.opensearch.OpenSearchException) Map(java.util.Map) HashMap(java.util.HashMap) Collections.singletonMap(java.util.Collections.singletonMap) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder)

Example 2 with LatchedActionListener

use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.

the class IndicesClientDocumentationIT method testCloneIndex.

public void testCloneIndex() throws Exception {
    RestHighLevelClient client = highLevelClient();
    {
        createIndex("source_index", Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0).build());
        updateIndexSettings("source_index", Settings.builder().put("index.blocks.write", true));
    }
    // tag::clone-index-request
    // <1>
    ResizeRequest request = new ResizeRequest("target_index", "source_index");
    // <2>
    request.setResizeType(ResizeType.CLONE);
    // end::clone-index-request
    // tag::clone-index-request-timeout
    // <1>
    request.timeout(TimeValue.timeValueMinutes(2));
    // <2>
    request.timeout("2m");
    // end::clone-index-request-timeout
    // tag::clone-index-request-masterTimeout
    // <1>
    request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
    // <2>
    request.masterNodeTimeout("1m");
    // end::clone-index-request-masterTimeout
    // tag::clone-index-request-waitForActiveShards
    // <1>
    request.setWaitForActiveShards(2);
    // <2>
    request.setWaitForActiveShards(ActiveShardCount.DEFAULT);
    // end::clone-index-request-waitForActiveShards
    // tag::clone-index-request-settings
    request.getTargetIndexRequest().settings(Settings.builder().put("index.number_of_shards", // <1>
    2));
    // end::clone-index-request-settings
    // tag::clone-index-request-aliases
    // <1>
    request.getTargetIndexRequest().alias(new Alias("target_alias"));
    // end::clone-index-request-aliases
    // tag::clone-index-execute
    ResizeResponse resizeResponse = client.indices().clone(request, RequestOptions.DEFAULT);
    // end::clone-index-execute
    // tag::clone-index-response
    // <1>
    boolean acknowledged = resizeResponse.isAcknowledged();
    // <2>
    boolean shardsAcked = resizeResponse.isShardsAcknowledged();
    // end::clone-index-response
    assertTrue(acknowledged);
    assertTrue(shardsAcked);
    // tag::clone-index-execute-listener
    ActionListener<ResizeResponse> listener = new ActionListener<ResizeResponse>() {

        @Override
        public void onResponse(ResizeResponse resizeResponse) {
        // <1>
        }

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::clone-index-execute-listener
    // Replace the empty listener by a blocking listener in test
    final CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::clone-index-execute-async
    // <1>
    client.indices().cloneAsync(request, RequestOptions.DEFAULT, listener);
    // end::clone-index-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : ResizeResponse(org.opensearch.action.admin.indices.shrink.ResizeResponse) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) Alias(org.opensearch.action.admin.indices.alias.Alias) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) CountDownLatch(java.util.concurrent.CountDownLatch) ResizeRequest(org.opensearch.action.admin.indices.shrink.ResizeRequest) IOException(java.io.IOException) DefaultShardOperationFailedException(org.opensearch.action.support.DefaultShardOperationFailedException) OpenSearchException(org.opensearch.OpenSearchException)

Example 3 with LatchedActionListener

use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.

the class IndicesClientDocumentationIT method testSimulateIndexTemplate.

public void testSimulateIndexTemplate() throws Exception {
    RestHighLevelClient client = highLevelClient();
    {
        // <1>
        PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest().name("my-template");
        Template template = new Template(Settings.builder().put("index.number_of_replicas", 3).build(), null, null);
        ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), template, null, null, null, null);
        request.indexTemplate(composableIndexTemplate);
        assertTrue(client.indices().putIndexTemplate(request, RequestOptions.DEFAULT).isAcknowledged());
    }
    // tag::simulate-index-template-request
    // <1>
    SimulateIndexTemplateRequest simulateRequest = new SimulateIndexTemplateRequest("log-000001");
    PutComposableIndexTemplateRequest newIndexTemplateRequest = new PutComposableIndexTemplateRequest().name("used-for-simulation");
    Settings settings = Settings.builder().put("index.number_of_shards", 6).build();
    // <2>
    Template template = new Template(settings, null, null);
    ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate(Arrays.asList("log-*"), template, null, 90L, null, null);
    newIndexTemplateRequest.indexTemplate(composableIndexTemplate);
    // <2>
    simulateRequest.indexTemplateV2Request(newIndexTemplateRequest);
    // end::simulate-index-template-request
    // tag::simulate-index-template-response
    SimulateIndexTemplateResponse simulateIndexTemplateResponse = client.indices().simulateIndexTemplate(simulateRequest, RequestOptions.DEFAULT);
    // <1>
    assertThat(simulateIndexTemplateResponse.resolvedTemplate().settings().get("index.number_of_shards"), is("6"));
    assertThat(simulateIndexTemplateResponse.overlappingTemplates().get("my-template"), // <2>
    containsInAnyOrder("pattern-1", "log-*"));
    // end::simulate-index-template-response
    // tag::simulate-index-template-execute-listener
    ActionListener<SimulateIndexTemplateResponse> listener = new ActionListener<SimulateIndexTemplateResponse>() {

        @Override
        public void onResponse(SimulateIndexTemplateResponse response) {
        // <1>
        }

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::simulate-index-template-execute-listener
    final CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::simulate-index-template-execute-async
    // <1>
    client.indices().simulateIndexTemplateAsync(simulateRequest, RequestOptions.DEFAULT, listener);
    // end::simulate-index-template-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : ComposableIndexTemplate(org.opensearch.cluster.metadata.ComposableIndexTemplate) SimulateIndexTemplateRequest(org.opensearch.client.indices.SimulateIndexTemplateRequest) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) SimulateIndexTemplateResponse(org.opensearch.client.indices.SimulateIndexTemplateResponse) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) CountDownLatch(java.util.concurrent.CountDownLatch) PutComposableIndexTemplateRequest(org.opensearch.client.indices.PutComposableIndexTemplateRequest) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) IOException(java.io.IOException) DefaultShardOperationFailedException(org.opensearch.action.support.DefaultShardOperationFailedException) OpenSearchException(org.opensearch.OpenSearchException) ComponentTemplate(org.opensearch.cluster.metadata.ComponentTemplate) ComposableIndexTemplate(org.opensearch.cluster.metadata.ComposableIndexTemplate) Template(org.opensearch.cluster.metadata.Template)

Example 4 with LatchedActionListener

use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.

the class IndicesClientDocumentationIT method testIndexPutSettings.

@SuppressWarnings("unused")
public void testIndexPutSettings() throws Exception {
    RestHighLevelClient client = highLevelClient();
    {
        CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("index"), RequestOptions.DEFAULT);
        assertTrue(createIndexResponse.isAcknowledged());
    }
    // tag::indices-put-settings-request
    // <1>
    UpdateSettingsRequest request = new UpdateSettingsRequest("index1");
    UpdateSettingsRequest requestMultiple = // <2>
    new UpdateSettingsRequest("index1", "index2");
    // <3>
    UpdateSettingsRequest requestAll = new UpdateSettingsRequest();
    // end::indices-put-settings-request
    // tag::indices-put-settings-create-settings
    String settingKey = "index.number_of_replicas";
    int settingValue = 0;
    Settings settings = Settings.builder().put(settingKey, settingValue).build();
    // end::indices-put-settings-create-settings
    // tag::indices-put-settings-request-index-settings
    request.settings(settings);
    // end::indices-put-settings-request-index-settings
    {
        // tag::indices-put-settings-settings-builder
        Settings.Builder settingsBuilder = Settings.builder().put(settingKey, settingValue);
        // <1>
        request.settings(settingsBuilder);
    // end::indices-put-settings-settings-builder
    }
    {
        // tag::indices-put-settings-settings-map
        Map<String, Object> map = new HashMap<>();
        map.put(settingKey, settingValue);
        // <1>
        request.settings(map);
    // end::indices-put-settings-settings-map
    }
    {
        // tag::indices-put-settings-settings-source
        request.settings("{\"index.number_of_replicas\": \"2\"}", // <1>
        XContentType.JSON);
    // end::indices-put-settings-settings-source
    }
    // tag::indices-put-settings-request-preserveExisting
    // <1>
    request.setPreserveExisting(false);
    // end::indices-put-settings-request-preserveExisting
    // tag::indices-put-settings-request-timeout
    // <1>
    request.timeout(TimeValue.timeValueMinutes(2));
    // <2>
    request.timeout("2m");
    // end::indices-put-settings-request-timeout
    // tag::indices-put-settings-request-masterTimeout
    // <1>
    request.masterNodeTimeout(TimeValue.timeValueMinutes(1));
    // <2>
    request.masterNodeTimeout("1m");
    // end::indices-put-settings-request-masterTimeout
    // tag::indices-put-settings-request-indicesOptions
    // <1>
    request.indicesOptions(IndicesOptions.lenientExpandOpen());
    // end::indices-put-settings-request-indicesOptions
    // tag::indices-put-settings-execute
    AcknowledgedResponse updateSettingsResponse = client.indices().putSettings(request, RequestOptions.DEFAULT);
    // end::indices-put-settings-execute
    // tag::indices-put-settings-response
    // <1>
    boolean acknowledged = updateSettingsResponse.isAcknowledged();
    // end::indices-put-settings-response
    assertTrue(acknowledged);
    // tag::indices-put-settings-execute-listener
    ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {

        @Override
        public void onResponse(AcknowledgedResponse updateSettingsResponse) {
        // <1>
        }

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::indices-put-settings-execute-listener
    // Replace the empty listener by a blocking listener in test
    final CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::indices-put-settings-execute-async
    // <1>
    client.indices().putSettingsAsync(request, RequestOptions.DEFAULT, listener);
    // end::indices-put-settings-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : UpdateSettingsRequest(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) DefaultShardOperationFailedException(org.opensearch.action.support.DefaultShardOperationFailedException) OpenSearchException(org.opensearch.OpenSearchException) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) CreateIndexResponse(org.opensearch.client.indices.CreateIndexResponse) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) Map(java.util.Map) HashMap(java.util.HashMap) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 5 with LatchedActionListener

use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.

the class IndicesClientDocumentationIT method testGetFieldMapping.

@SuppressWarnings("unused")
public void testGetFieldMapping() throws IOException, InterruptedException {
    RestHighLevelClient client = highLevelClient();
    {
        CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT);
        assertTrue(createIndexResponse.isAcknowledged());
        PutMappingRequest request = new PutMappingRequest("twitter");
        request.source("{\n" + "  \"properties\": {\n" + "    \"message\": {\n" + "      \"type\": \"text\"\n" + "    },\n" + "    \"timestamp\": {\n" + "      \"type\": \"date\"\n" + "    }\n" + "  }\n" + // <1>
        "}", XContentType.JSON);
        AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
        assertTrue(putMappingResponse.isAcknowledged());
    }
    // tag::get-field-mappings-request
    // <1>
    GetFieldMappingsRequest request = new GetFieldMappingsRequest();
    // <2>
    request.indices("twitter");
    // <3>
    request.fields("message", "timestamp");
    // end::get-field-mappings-request
    // tag::get-field-mappings-request-indicesOptions
    // <1>
    request.indicesOptions(IndicesOptions.lenientExpandOpen());
    // end::get-field-mappings-request-indicesOptions
    // tag::get-field-mappings-request-local
    // <1>
    request.local(true);
    // end::get-field-mappings-request-local
    {
        // tag::get-field-mappings-execute
        GetFieldMappingsResponse response = client.indices().getFieldMapping(request, RequestOptions.DEFAULT);
        // end::get-field-mappings-execute
        // tag::get-field-mappings-response
        final Map<String, Map<String, GetFieldMappingsResponse.FieldMappingMetadata>> mappings = // <1>
        response.mappings();
        final Map<String, GetFieldMappingsResponse.FieldMappingMetadata> fieldMappings = // <2>
        mappings.get("twitter");
        final GetFieldMappingsResponse.FieldMappingMetadata metadata = // <3>
        fieldMappings.get("message");
        // <4>
        final String fullName = metadata.fullName();
        // <5>
        final Map<String, Object> source = metadata.sourceAsMap();
    // end::get-field-mappings-response
    }
    {
        // tag::get-field-mappings-execute-listener
        ActionListener<GetFieldMappingsResponse> listener = new ActionListener<GetFieldMappingsResponse>() {

            @Override
            public void onResponse(GetFieldMappingsResponse putMappingResponse) {
            // <1>
            }

            @Override
            public void onFailure(Exception e) {
            // <2>
            }
        };
        // end::get-field-mappings-execute-listener
        // Replace the empty listener by a blocking listener in test
        final CountDownLatch latch = new CountDownLatch(1);
        final ActionListener<GetFieldMappingsResponse> latchListener = new LatchedActionListener<>(listener, latch);
        listener = ActionListener.wrap(r -> {
            final Map<String, Map<String, GetFieldMappingsResponse.FieldMappingMetadata>> mappings = r.mappings();
            final Map<String, GetFieldMappingsResponse.FieldMappingMetadata> fieldMappings = mappings.get("twitter");
            final GetFieldMappingsResponse.FieldMappingMetadata metadata1 = fieldMappings.get("message");
            final String fullName = metadata1.fullName();
            final Map<String, Object> source = metadata1.sourceAsMap();
            latchListener.onResponse(r);
        }, e -> {
            latchListener.onFailure(e);
            fail("should not fail");
        });
        // tag::get-field-mappings-execute-async
        // <1>
        client.indices().getFieldMappingAsync(request, RequestOptions.DEFAULT, listener);
        // end::get-field-mappings-execute-async
        assertTrue(latch.await(30L, TimeUnit.SECONDS));
    }
}
Also used : PutMappingRequest(org.opensearch.client.indices.PutMappingRequest) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) GetFieldMappingsRequest(org.opensearch.client.indices.GetFieldMappingsRequest) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) GetFieldMappingsResponse(org.opensearch.client.indices.GetFieldMappingsResponse) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) DefaultShardOperationFailedException(org.opensearch.action.support.DefaultShardOperationFailedException) OpenSearchException(org.opensearch.OpenSearchException) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) CreateIndexResponse(org.opensearch.client.indices.CreateIndexResponse) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

CountDownLatch (java.util.concurrent.CountDownLatch)50 LatchedActionListener (org.opensearch.action.LatchedActionListener)50 ActionListener (org.opensearch.action.ActionListener)49 IOException (java.io.IOException)41 RestHighLevelClient (org.opensearch.client.RestHighLevelClient)38 OpenSearchException (org.opensearch.OpenSearchException)24 HashMap (java.util.HashMap)20 Map (java.util.Map)19 DefaultShardOperationFailedException (org.opensearch.action.support.DefaultShardOperationFailedException)18 Matchers.containsString (org.hamcrest.Matchers.containsString)14 CreateIndexRequest (org.opensearch.client.indices.CreateIndexRequest)12 Settings (org.opensearch.common.settings.Settings)12 CreateIndexResponse (org.opensearch.client.indices.CreateIndexResponse)11 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)10 AcknowledgedResponse (org.opensearch.action.support.master.AcknowledgedResponse)10 List (java.util.List)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ArrayList (java.util.ArrayList)8 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)8 IndexSettings (org.opensearch.index.IndexSettings)8