Search in sources :

Example 26 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 27 with RestHighLevelClient

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

the class SearchDocumentationIT method testMultiSearch.

public void testMultiSearch() throws Exception {
    indexSearchTestData();
    RestHighLevelClient client = highLevelClient();
    {
        // tag::multi-search-request-basic
        // <1>
        MultiSearchRequest request = new MultiSearchRequest();
        // <2>
        SearchRequest firstSearchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("user", "foobar"));
        firstSearchRequest.source(searchSourceBuilder);
        // <3>
        request.add(firstSearchRequest);
        // <4>
        SearchRequest secondSearchRequest = new SearchRequest();
        searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("user", "quxx"));
        secondSearchRequest.source(searchSourceBuilder);
        request.add(secondSearchRequest);
        // end::multi-search-request-basic
        // tag::multi-search-execute
        MultiSearchResponse response = client.msearch(request, RequestOptions.DEFAULT);
        // end::multi-search-execute
        // tag::multi-search-response
        // <1>
        MultiSearchResponse.Item firstResponse = response.getResponses()[0];
        // <2>
        assertNull(firstResponse.getFailure());
        // <3>
        SearchResponse searchResponse = firstResponse.getResponse();
        assertEquals(4, searchResponse.getHits().getTotalHits().value);
        // <4>
        MultiSearchResponse.Item secondResponse = response.getResponses()[1];
        assertNull(secondResponse.getFailure());
        searchResponse = secondResponse.getResponse();
        assertEquals(1, searchResponse.getHits().getTotalHits().value);
        // end::multi-search-response
        // tag::multi-search-execute-listener
        ActionListener<MultiSearchResponse> listener = new ActionListener<MultiSearchResponse>() {

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

            @Override
            public void onFailure(Exception e) {
            // <2>
            }
        };
        // end::multi-search-execute-listener
        // Replace the empty listener by a blocking listener in test
        final CountDownLatch latch = new CountDownLatch(1);
        listener = new LatchedActionListener<>(listener, latch);
        // tag::multi-search-execute-async
        // <1>
        client.msearchAsync(request, RequestOptions.DEFAULT, listener);
        // end::multi-search-execute-async
        assertTrue(latch.await(30L, TimeUnit.SECONDS));
    }
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) Item(org.opensearch.script.mustache.MultiSearchTemplateResponse.Item) LatchedActionListener(org.opensearch.action.LatchedActionListener) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest)

Example 28 with RestHighLevelClient

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

the class SearchDocumentationIT method testMultiSearchTemplateWithStoredScript.

public void testMultiSearchTemplateWithStoredScript() throws Exception {
    indexSearchTestData();
    RestHighLevelClient client = highLevelClient();
    RestClient restClient = client();
    registerQueryScript(restClient);
    // tag::multi-search-template-request-stored
    MultiSearchTemplateRequest multiRequest = new MultiSearchTemplateRequest();
    String[] searchTerms = { "opensearch", "dashboards" };
    for (String searchTerm : searchTerms) {
        SearchTemplateRequest request = new SearchTemplateRequest();
        request.setRequest(new SearchRequest("posts"));
        request.setScriptType(ScriptType.STORED);
        request.setScript("title_search");
        Map<String, Object> params = new HashMap<>();
        params.put("field", "title");
        params.put("value", searchTerm);
        params.put("size", 5);
        request.setScriptParams(params);
        multiRequest.add(request);
    }
    // end::multi-search-template-request-stored
    // tag::multi-search-template-execute
    MultiSearchTemplateResponse multiResponse = client.msearchTemplate(multiRequest, RequestOptions.DEFAULT);
    // end::multi-search-template-execute
    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);
    // tag::multi-search-template-execute-listener
    ActionListener<MultiSearchTemplateResponse> listener = new ActionListener<MultiSearchTemplateResponse>() {

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

        @Override
        public void onFailure(Exception e) {
        // <2>
        }
    };
    // end::multi-search-template-execute-listener
    // Replace the empty listener by a blocking listener for tests.
    CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);
    // tag::multi-search-template-execute-async
    client.msearchTemplateAsync(multiRequest, RequestOptions.DEFAULT, listener);
    // end::multi-search-template-execute-async
    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) HashMap(java.util.HashMap) RestClient(org.opensearch.client.RestClient) MultiSearchTemplateResponse(org.opensearch.script.mustache.MultiSearchTemplateResponse) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest) LatchedActionListener(org.opensearch.action.LatchedActionListener) ActionListener(org.opensearch.action.ActionListener) SearchTemplateRequest(org.opensearch.script.mustache.SearchTemplateRequest) MultiSearchTemplateRequest(org.opensearch.script.mustache.MultiSearchTemplateRequest)

Example 29 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 30 with RestHighLevelClient

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

the class SearchDocumentationIT method testSearchRequestSuggestions.

@SuppressWarnings({ "unused", "rawtypes" })
public void testSearchRequestSuggestions() throws IOException {
    RestHighLevelClient client = highLevelClient();
    {
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest("posts").id("1").source(XContentType.JSON, "user", "foobar"));
        request.add(new IndexRequest("posts").id("2").source(XContentType.JSON, "user", "quxx"));
        request.add(new IndexRequest("posts").id("3").source(XContentType.JSON, "user", "quzz"));
        request.add(new IndexRequest("posts").id("4").source(XContentType.JSON, "user", "corge"));
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
        assertSame(RestStatus.OK, bulkResponse.status());
        assertFalse(bulkResponse.hasFailures());
    }
    {
        SearchRequest searchRequest = new SearchRequest();
        // tag::search-request-suggestion
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        SuggestionBuilder termSuggestionBuilder = // <1>
        SuggestBuilders.termSuggestion("user").text("fooarb");
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        // <2>
        suggestBuilder.addSuggestion("suggest_user", termSuggestionBuilder);
        searchSourceBuilder.suggest(suggestBuilder);
        // end::search-request-suggestion
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        {
            // tag::search-request-suggestion-get
            // <1>
            Suggest suggest = searchResponse.getSuggest();
            // <2>
            TermSuggestion termSuggestion = suggest.getSuggestion("suggest_user");
            for (TermSuggestion.Entry entry : termSuggestion.getEntries()) {
                // <3>
                for (TermSuggestion.Entry.Option option : entry) {
                    // <4>
                    String suggestText = option.getText().string();
                }
            }
            // end::search-request-suggestion-get
            assertEquals(1, termSuggestion.getEntries().size());
            assertEquals(1, termSuggestion.getEntries().get(0).getOptions().size());
            assertEquals("foobar", termSuggestion.getEntries().get(0).getOptions().get(0).getText().string());
        }
    }
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) BulkResponse(org.opensearch.action.bulk.BulkResponse) RestHighLevelClient(org.opensearch.client.RestHighLevelClient) Matchers.containsString(org.hamcrest.Matchers.containsString) CreateIndexRequest(org.opensearch.client.indices.CreateIndexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) Suggest(org.opensearch.search.suggest.Suggest) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) BulkRequest(org.opensearch.action.bulk.BulkRequest) TermSuggestion(org.opensearch.search.suggest.term.TermSuggestion) SuggestionBuilder(org.opensearch.search.suggest.SuggestionBuilder)

Aggregations

RestHighLevelClient (org.opensearch.client.RestHighLevelClient)95 CountDownLatch (java.util.concurrent.CountDownLatch)42 IOException (java.io.IOException)40 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)21 DefaultShardOperationFailedException (org.opensearch.action.support.DefaultShardOperationFailedException)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 AcknowledgedResponse (org.opensearch.action.support.master.AcknowledgedResponse)16 CreateIndexResponse (org.opensearch.client.indices.CreateIndexResponse)15 Test (org.junit.Test)14 IndexRequest (org.opensearch.action.index.IndexRequest)14 Settings (org.opensearch.common.settings.Settings)13 SearchRequest (org.opensearch.action.search.SearchRequest)12 SearchResponse (org.opensearch.action.search.SearchResponse)12 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)10 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)10