Search in sources :

Example 16 with RestHighLevelClient

use of org.opensearch.client.RestHighLevelClient in project OpenSearch by opensearch-project.

the class SearchDocumentationIT method testMultiSearchTemplateWithInlineScript.

@SuppressWarnings("unused")
public void testMultiSearchTemplateWithInlineScript() throws Exception {
    indexSearchTestData();
    RestHighLevelClient client = highLevelClient();
    // tag::multi-search-template-request-inline
    String[] searchTerms = { "opensearch", "opensearch-dashboards" };
    // <1>
    MultiSearchTemplateRequest multiRequest = new MultiSearchTemplateRequest();
    for (String searchTerm : searchTerms) {
        // <2>
        SearchTemplateRequest request = new SearchTemplateRequest();
        request.setRequest(new SearchRequest("posts"));
        request.setScriptType(ScriptType.INLINE);
        request.setScript("{" + "  \"query\": { \"match\" : { \"{{field}}\" : \"{{value}}\" } }," + "  \"size\" : \"{{size}}\"" + "}");
        Map<String, Object> scriptParams = new HashMap<>();
        scriptParams.put("field", "title");
        scriptParams.put("value", searchTerm);
        scriptParams.put("size", 5);
        request.setScriptParams(scriptParams);
        // <3>
        multiRequest.add(request);
    }
    // end::multi-search-template-request-inline
    // tag::multi-search-template-request-sync
    MultiSearchTemplateResponse multiResponse = client.msearchTemplate(multiRequest, RequestOptions.DEFAULT);
    // tag::multi-search-template-response
    for (Item item : multiResponse.getResponses()) {
        // <1>
        if (item.isFailure()) {
            // <2>
            String error = item.getFailureMessage();
        } else {
            // <3>
            SearchTemplateResponse searchTemplateResponse = item.getResponse();
            SearchResponse searchResponse = searchTemplateResponse.getResponse();
            searchResponse.getHits();
        }
    }
    // end::multi-search-template-response
    assertNotNull(multiResponse);
    assertEquals(searchTerms.length, multiResponse.getResponses().length);
    assertNotNull(multiResponse.getResponses()[0]);
    SearchResponse searchResponse = multiResponse.getResponses()[0].getResponse().getResponse();
    assertTrue(searchResponse.getHits().getTotalHits().value > 0);
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) HashMap(java.util.HashMap) MultiSearchTemplateResponse(org.opensearch.script.mustache.MultiSearchTemplateResponse) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) Matchers.containsString(org.hamcrest.Matchers.containsString) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) Item(org.opensearch.script.mustache.MultiSearchTemplateResponse.Item) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) SearchTemplateResponse(org.opensearch.script.mustache.SearchTemplateResponse) MultiSearchTemplateResponse(org.opensearch.script.mustache.MultiSearchTemplateResponse)

Example 17 with RestHighLevelClient

use of org.opensearch.client.RestHighLevelClient in project OpenSearch by opensearch-project.

the class SearchDocumentationIT method testExplain.

public void testExplain() throws Exception {
    indexSearchTestData();
    RestHighLevelClient client = highLevelClient();
    // tag::explain-request
    ExplainRequest request = new ExplainRequest("contributors", "1");
    request.query(QueryBuilders.termQuery("user", "quuz"));
    // end::explain-request
    // tag::explain-request-routing
    // <1>
    request.routing("routing");
    // end::explain-request-routing
    // tag::explain-request-preference
    // <1>
    request.preference("_local");
    // end::explain-request-preference
    // tag::explain-request-source
    // <1>
    request.fetchSourceContext(new FetchSourceContext(true, new String[] { "user" }, null));
    // end::explain-request-source
    // tag::explain-request-stored-field
    // <1>
    request.storedFields(new String[] { "user" });
    // end::explain-request-stored-field
    // tag::explain-execute
    ExplainResponse response = client.explain(request, RequestOptions.DEFAULT);
    // end::explain-execute
    // tag::explain-response
    // <1>
    String index = response.getIndex();
    // <2>
    String id = response.getId();
    // <3>
    boolean exists = response.isExists();
    // <4>
    boolean match = response.isMatch();
    // <5>
    boolean hasExplanation = response.hasExplanation();
    // <6>
    Explanation explanation = response.getExplanation();
    // <7>
    GetResult getResult = response.getGetResult();
    // end::explain-response
    assertThat(index, equalTo("contributors"));
    assertThat(id, equalTo("1"));
    assertTrue(exists);
    assertTrue(match);
    assertTrue(hasExplanation);
    assertNotNull(explanation);
    assertNotNull(getResult);
    // tag::get-result
    // <1>
    Map<String, Object> source = getResult.getSource();
    // <2>
    Map<String, DocumentField> fields = getResult.getFields();
    // end::get-result
    assertThat(source, equalTo(Collections.singletonMap("user", "quuz")));
    assertThat(fields.get("user").getValue(), equalTo("quuz"));
    // tag::explain-execute-listener
    ActionListener<ExplainResponse> listener = new ActionListener<ExplainResponse>() {

        @Override
        public void onResponse(ExplainResponse explainResponse) {
        // <1>
        }

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::explain-execute-listener
    CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::explain-execute-async
    // <1>
    client.explainAsync(request, RequestOptions.DEFAULT, listener);
    // end::explain-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : GetResult(org.opensearch.index.get.GetResult) DocumentField(org.opensearch.common.document.DocumentField) Explanation(org.apache.lucene.search.Explanation) ExplainResponse(org.opensearch.action.explain.ExplainResponse) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) Matchers.containsString(org.hamcrest.Matchers.containsString) ExplainRequest(org.opensearch.action.explain.ExplainRequest) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) FetchSourceContext(org.opensearch.search.fetch.subphase.FetchSourceContext) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener)

Example 18 with RestHighLevelClient

use of org.opensearch.client.RestHighLevelClient in project OpenSearch by opensearch-project.

the class CRUDDocumentationIT method testReindexRethrottle.

@SuppressWarnings("unused")
public void testReindexRethrottle() throws Exception {
    RestHighLevelClient client = highLevelClient();
    TaskId taskId = new TaskId("oTUltX4IQMOUUVeiohTt8A:124");
    {
        // tag::rethrottle-disable-request
        // <1>
        RethrottleRequest request = new RethrottleRequest(taskId);
    // end::rethrottle-disable-request
    }
    {
        // tag::rethrottle-request
        // <1>
        RethrottleRequest request = new RethrottleRequest(taskId, 100.0f);
    // end::rethrottle-request
    }
    {
        RethrottleRequest request = new RethrottleRequest(taskId);
        // tag::rethrottle-request-execution
        // <1>
        client.reindexRethrottle(request, RequestOptions.DEFAULT);
        // <2>
        client.updateByQueryRethrottle(request, RequestOptions.DEFAULT);
        // <3>
        client.deleteByQueryRethrottle(request, RequestOptions.DEFAULT);
    // end::rethrottle-request-execution
    }
    ActionListener<ListTasksResponse> listener;
    // tag::rethrottle-request-async-listener
    listener = new ActionListener<ListTasksResponse>() {

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

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::rethrottle-request-async-listener
    // Replace the empty listener by a blocking listener in test
    final CountDownLatch latch = new CountDownLatch(3);
    listener = new LatchedActionListener<>(listener, latch);
    RethrottleRequest request = new RethrottleRequest(taskId);
    // tag::rethrottle-execute-async
    client.reindexRethrottleAsync(request, RequestOptions.DEFAULT, // <1>
    listener);
    client.updateByQueryRethrottleAsync(request, RequestOptions.DEFAULT, // <2>
    listener);
    client.deleteByQueryRethrottleAsync(request, RequestOptions.DEFAULT, // <3>
    listener);
    // end::rethrottle-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : RethrottleRequest(org.opensearch.client.RethrottleRequest) TaskId(org.opensearch.tasks.TaskId) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) ListTasksResponse(org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchException(org.opensearch.OpenSearchException)

Example 19 with RestHighLevelClient

use of org.opensearch.client.RestHighLevelClient in project OpenSearch by opensearch-project.

the class CRUDDocumentationIT method testMultiTermVectors.

// Not entirely sure if _mtermvectors belongs to CRUD, and in the absence of a better place, will have it here
public void testMultiTermVectors() throws Exception {
    RestHighLevelClient client = highLevelClient();
    CreateIndexRequest authorsRequest = new CreateIndexRequest("authors").mapping(XContentFactory.jsonBuilder().startObject().startObject("properties").startObject("user").field("type", "keyword").endObject().endObject().endObject());
    CreateIndexResponse authorsResponse = client.indices().create(authorsRequest, RequestOptions.DEFAULT);
    assertTrue(authorsResponse.isAcknowledged());
    client.index(new IndexRequest("index").id("1").source("user", "foobar"), RequestOptions.DEFAULT);
    client.index(new IndexRequest("index").id("2").source("user", "baz"), RequestOptions.DEFAULT);
    Response refreshResponse = client().performRequest(new Request("POST", "/authors/_refresh"));
    assertEquals(200, refreshResponse.getStatusLine().getStatusCode());
    {
        // tag::multi-term-vectors-request
        // <1>
        MultiTermVectorsRequest request = new MultiTermVectorsRequest();
        TermVectorsRequest tvrequest1 = new TermVectorsRequest("authors", "1");
        tvrequest1.setFields("user");
        // <2>
        request.add(tvrequest1);
        XContentBuilder docBuilder = XContentFactory.jsonBuilder();
        docBuilder.startObject().field("user", "guest-user").endObject();
        TermVectorsRequest tvrequest2 = new TermVectorsRequest("authors", docBuilder);
        // <3>
        request.add(tvrequest2);
    // end::multi-term-vectors-request
    }
    // tag::multi-term-vectors-request-template
    TermVectorsRequest tvrequestTemplate = // <1>
    new TermVectorsRequest("authors", "fake_id");
    tvrequestTemplate.setFields("user");
    String[] ids = { "1", "2" };
    MultiTermVectorsRequest request = // <2>
    new MultiTermVectorsRequest(ids, tvrequestTemplate);
    // end::multi-term-vectors-request-template
    // tag::multi-term-vectors-execute
    MultiTermVectorsResponse response = client.mtermvectors(request, RequestOptions.DEFAULT);
    // end::multi-term-vectors-execute
    // tag::multi-term-vectors-response
    List<TermVectorsResponse> tvresponseList = // <1>
    response.getTermVectorsResponses();
    if (tvresponseList != null) {
        for (TermVectorsResponse tvresponse : tvresponseList) {
        }
    }
    // end::multi-term-vectors-response
    ActionListener<MultiTermVectorsResponse> listener;
    // tag::multi-term-vectors-execute-listener
    listener = new ActionListener<MultiTermVectorsResponse>() {

        @Override
        public void onResponse(MultiTermVectorsResponse mtvResponse) {
        // <1>
        }

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::multi-term-vectors-execute-listener
    CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::multi-term-vectors-execute-async
    client.mtermvectorsAsync(request, RequestOptions.DEFAULT, // <1>
    listener);
    // end::multi-term-vectors-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : TermVectorsRequest(org.opensearch.client.core.TermVectorsRequest) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) MultiTermVectorsResponse(org.opensearch.client.core.MultiTermVectorsResponse) TermVectorsResponse(org.opensearch.client.core.TermVectorsResponse) 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) MultiTermVectorsResponse(org.opensearch.client.core.MultiTermVectorsResponse) OpenSearchException(org.opensearch.OpenSearchException) 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) MultiTermVectorsRequest(org.opensearch.client.core.MultiTermVectorsRequest) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) CreateIndexResponse(org.opensearch.client.indices.CreateIndexResponse) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder)

Example 20 with RestHighLevelClient

use of org.opensearch.client.RestHighLevelClient in project OpenSearch by opensearch-project.

the class ClusterClientDocumentationIT method testGetComponentTemplates.

public void testGetComponentTemplates() throws Exception {
    RestHighLevelClient client = highLevelClient();
    {
        Template template = new Template(Settings.builder().put("index.number_of_replicas", 3).build(), null, null);
        ComponentTemplate componentTemplate = new ComponentTemplate(template, null, null);
        PutComponentTemplateRequest putComponentTemplateRequest = new PutComponentTemplateRequest().name("ct1").componentTemplate(componentTemplate);
        client.cluster().putComponentTemplate(putComponentTemplateRequest, RequestOptions.DEFAULT);
        assertTrue(client.cluster().putComponentTemplate(putComponentTemplateRequest, RequestOptions.DEFAULT).isAcknowledged());
    }
    // tag::get-component-templates-request
    // <1>
    GetComponentTemplatesRequest request = new GetComponentTemplatesRequest("ct1");
    // end::get-component-templates-request
    // tag::get-component-templates-request-masterTimeout
    // <1>
    request.setMasterNodeTimeout(TimeValue.timeValueMinutes(1));
    // <2>
    request.setMasterNodeTimeout("1m");
    // end::get-component-templates-request-masterTimeout
    // tag::get-component-templates-execute
    GetComponentTemplatesResponse getTemplatesResponse = client.cluster().getComponentTemplate(request, RequestOptions.DEFAULT);
    // end::get-component-templates-execute
    // tag::get-component-templates-response
    // <1>
    Map<String, ComponentTemplate> templates = getTemplatesResponse.getComponentTemplates();
    // end::get-component-templates-response
    assertThat(templates.size(), is(1));
    assertThat(templates.get("ct1"), is(notNullValue()));
    // tag::get-component-templates-execute-listener
    ActionListener<GetComponentTemplatesResponse> listener = new ActionListener<GetComponentTemplatesResponse>() {

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

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::get-component-templates-execute-listener
    // Replace the empty listener by a blocking listener in test
    final CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::get-component-templates-execute-async
    // <1>
    client.cluster().getComponentTemplateAsync(request, RequestOptions.DEFAULT, listener);
    // end::get-component-templates-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : GetComponentTemplatesRequest(org.opensearch.client.indices.GetComponentTemplatesRequest) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) Template(org.opensearch.cluster.metadata.Template) ComponentTemplate(org.opensearch.cluster.metadata.ComponentTemplate) PutComponentTemplateRequest(org.opensearch.client.indices.PutComponentTemplateRequest) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) ComponentTemplate(org.opensearch.cluster.metadata.ComponentTemplate) GetComponentTemplatesResponse(org.opensearch.client.indices.GetComponentTemplatesResponse)

Aggregations

RestHighLevelClient (org.opensearch.client.RestHighLevelClient)102 IOException (java.io.IOException)42 CountDownLatch (java.util.concurrent.CountDownLatch)42 ActionListener (org.opensearch.action.ActionListener)38 LatchedActionListener (org.opensearch.action.LatchedActionListener)38 OpenSearchException (org.opensearch.OpenSearchException)30 HashMap (java.util.HashMap)29 Map (java.util.Map)27 CreateIndexRequest (org.opensearch.client.indices.CreateIndexRequest)23 DefaultShardOperationFailedException (org.opensearch.action.support.DefaultShardOperationFailedException)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 AcknowledgedResponse (org.opensearch.action.support.master.AcknowledgedResponse)16 Test (org.junit.Test)15 CreateIndexResponse (org.opensearch.client.indices.CreateIndexResponse)15 IndexRequest (org.opensearch.action.index.IndexRequest)13 Settings (org.opensearch.common.settings.Settings)13 SearchRequest (org.opensearch.action.search.SearchRequest)12 SearchResponse (org.opensearch.action.search.SearchResponse)12 HttpHost (org.apache.http.HttpHost)11 Request (org.opensearch.client.Request)10