Search in sources :

Example 1 with SuggestBuilder

use of org.opensearch.search.suggest.SuggestBuilder in project OpenSearch by opensearch-project.

the class SearchIT method testSearchWithSuggest.

public void testSearchWithSuggest() throws IOException {
    SearchRequest searchRequest = new SearchRequest("index");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion("sugg1", new PhraseSuggestionBuilder("type")).setGlobalText("type"));
    searchSourceBuilder.size(0);
    searchRequest.source(searchSourceBuilder);
    SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync);
    assertSearchHeader(searchResponse);
    assertNull(searchResponse.getAggregations());
    assertEquals(Collections.emptyMap(), searchResponse.getProfileResults());
    assertEquals(0, searchResponse.getHits().getTotalHits().value);
    assertEquals(Float.NaN, searchResponse.getHits().getMaxScore(), 0f);
    assertEquals(0, searchResponse.getHits().getHits().length);
    assertEquals(1, searchResponse.getSuggest().size());
    Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> sugg = searchResponse.getSuggest().iterator().next();
    assertEquals("sugg1", sugg.getName());
    for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> options : sugg) {
        assertEquals("type", options.getText().string());
        assertEquals(0, options.getOffset());
        assertEquals(4, options.getLength());
        assertEquals(2, options.getOptions().size());
        for (Suggest.Suggestion.Entry.Option option : options) {
            assertThat(option.getScore(), greaterThan(0f));
            assertThat(option.getText().string(), either(equalTo("type1")).or(equalTo("type2")));
        }
    }
}
Also used : MultiSearchRequest(org.opensearch.action.search.MultiSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) PhraseSuggestionBuilder(org.opensearch.search.suggest.phrase.PhraseSuggestionBuilder) Suggest(org.opensearch.search.suggest.Suggest) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) MultiSearchResponse(org.opensearch.action.search.MultiSearchResponse) SearchResponse(org.opensearch.action.search.SearchResponse)

Example 2 with SuggestBuilder

use of org.opensearch.search.suggest.SuggestBuilder 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)

Example 3 with SuggestBuilder

use of org.opensearch.search.suggest.SuggestBuilder in project OpenSearch by opensearch-project.

the class CCSDuelIT method testPhraseSuggester.

public void testPhraseSuggester() throws Exception {
    assumeMultiClusterSetup();
    SearchRequest searchRequest = initSearchRequest();
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    searchRequest.source(sourceBuilder);
    SuggestBuilder suggestBuilder = new SuggestBuilder();
    suggestBuilder.setGlobalText("jva and hml");
    suggestBuilder.addSuggestion("tags", new PhraseSuggestionBuilder("tags").addCandidateGenerator(new DirectCandidateGeneratorBuilder("tags").suggestMode("always")).highlight("<em>", "</em>"));
    sourceBuilder.suggest(suggestBuilder);
    duelSearch(searchRequest, response -> {
        assertMultiClusterSearchResponse(response);
        assertEquals(1, response.getSuggest().size());
        PhraseSuggestion tags = response.getSuggest().getSuggestion("tags");
        assertThat(tags.getEntries().size(), greaterThan(0));
    });
}
Also used : SearchRequest(org.opensearch.action.search.SearchRequest) PhraseSuggestion(org.opensearch.search.suggest.phrase.PhraseSuggestion) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) PhraseSuggestionBuilder(org.opensearch.search.suggest.phrase.PhraseSuggestionBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) DirectCandidateGeneratorBuilder(org.opensearch.search.suggest.phrase.DirectCandidateGeneratorBuilder)

Example 4 with SuggestBuilder

use of org.opensearch.search.suggest.SuggestBuilder in project OpenSearch by opensearch-project.

the class RatedRequestsTests method testSuggestionsNotAllowed.

public void testSuggestionsNotAllowed() {
    List<RatedDocument> ratedDocs = Arrays.asList(new RatedDocument("index1", "id1", 1));
    SearchSourceBuilder query = new SearchSourceBuilder();
    query.suggest(new SuggestBuilder().addSuggestion("id", SuggestBuilders.completionSuggestion("fieldname")));
    IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new RatedRequest("id", ratedDocs, query));
    assertEquals("Query in rated requests should not contain a suggest section.", e.getMessage());
}
Also used : SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder)

Example 5 with SuggestBuilder

use of org.opensearch.search.suggest.SuggestBuilder in project OpenSearch by opensearch-project.

the class RestSearchAction method parseSearchSource.

/**
 * Parses the rest request on top of the SearchSourceBuilder, preserving
 * values that are not overridden by the rest request.
 */
private static void parseSearchSource(final SearchSourceBuilder searchSourceBuilder, RestRequest request, IntConsumer setSize) {
    QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request);
    if (queryBuilder != null) {
        searchSourceBuilder.query(queryBuilder);
    }
    int from = request.paramAsInt("from", -1);
    if (from != -1) {
        searchSourceBuilder.from(from);
    }
    int size = request.paramAsInt("size", -1);
    if (size != -1) {
        setSize.accept(size);
    }
    if (request.hasParam("explain")) {
        searchSourceBuilder.explain(request.paramAsBoolean("explain", null));
    }
    if (request.hasParam("version")) {
        searchSourceBuilder.version(request.paramAsBoolean("version", null));
    }
    if (request.hasParam("seq_no_primary_term")) {
        searchSourceBuilder.seqNoAndPrimaryTerm(request.paramAsBoolean("seq_no_primary_term", null));
    }
    if (request.hasParam("timeout")) {
        searchSourceBuilder.timeout(request.paramAsTime("timeout", null));
    }
    if (request.hasParam("terminate_after")) {
        int terminateAfter = request.paramAsInt("terminate_after", SearchContext.DEFAULT_TERMINATE_AFTER);
        if (terminateAfter < 0) {
            throw new IllegalArgumentException("terminateAfter must be > 0");
        } else if (terminateAfter > 0) {
            searchSourceBuilder.terminateAfter(terminateAfter);
        }
    }
    StoredFieldsContext storedFieldsContext = StoredFieldsContext.fromRestRequest(SearchSourceBuilder.STORED_FIELDS_FIELD.getPreferredName(), request);
    if (storedFieldsContext != null) {
        searchSourceBuilder.storedFields(storedFieldsContext);
    }
    String sDocValueFields = request.param("docvalue_fields");
    if (sDocValueFields != null) {
        if (Strings.hasText(sDocValueFields)) {
            String[] sFields = Strings.splitStringByCommaToArray(sDocValueFields);
            for (String field : sFields) {
                searchSourceBuilder.docValueField(field, null);
            }
        }
    }
    FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
    if (fetchSourceContext != null) {
        searchSourceBuilder.fetchSource(fetchSourceContext);
    }
    if (request.hasParam("track_scores")) {
        searchSourceBuilder.trackScores(request.paramAsBoolean("track_scores", false));
    }
    if (request.hasParam("track_total_hits")) {
        if (Booleans.isBoolean(request.param("track_total_hits"))) {
            searchSourceBuilder.trackTotalHits(request.paramAsBoolean("track_total_hits", true));
        } else {
            searchSourceBuilder.trackTotalHitsUpTo(request.paramAsInt("track_total_hits", SearchContext.DEFAULT_TRACK_TOTAL_HITS_UP_TO));
        }
    }
    String sSorts = request.param("sort");
    if (sSorts != null) {
        String[] sorts = Strings.splitStringByCommaToArray(sSorts);
        for (String sort : sorts) {
            int delimiter = sort.lastIndexOf(":");
            if (delimiter != -1) {
                String sortField = sort.substring(0, delimiter);
                String reverse = sort.substring(delimiter + 1);
                if ("asc".equals(reverse)) {
                    searchSourceBuilder.sort(sortField, SortOrder.ASC);
                } else if ("desc".equals(reverse)) {
                    searchSourceBuilder.sort(sortField, SortOrder.DESC);
                }
            } else {
                searchSourceBuilder.sort(sort);
            }
        }
    }
    String sStats = request.param("stats");
    if (sStats != null) {
        searchSourceBuilder.stats(Arrays.asList(Strings.splitStringByCommaToArray(sStats)));
    }
    String suggestField = request.param("suggest_field");
    if (suggestField != null) {
        String suggestText = request.param("suggest_text", request.param("q"));
        int suggestSize = request.paramAsInt("suggest_size", 5);
        String suggestMode = request.param("suggest_mode");
        searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion(suggestField, termSuggestion(suggestField).text(suggestText).size(suggestSize).suggestMode(SuggestMode.resolve(suggestMode))));
    }
}
Also used : StoredFieldsContext(org.opensearch.search.fetch.StoredFieldsContext) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) FetchSourceContext(org.opensearch.search.fetch.subphase.FetchSourceContext) QueryBuilder(org.opensearch.index.query.QueryBuilder)

Aggregations

SuggestBuilder (org.opensearch.search.suggest.SuggestBuilder)9 SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)7 SearchRequest (org.opensearch.action.search.SearchRequest)5 Matchers.containsString (org.hamcrest.Matchers.containsString)2 MultiSearchRequest (org.opensearch.action.search.MultiSearchRequest)2 MultiSearchResponse (org.opensearch.action.search.MultiSearchResponse)2 SearchResponse (org.opensearch.action.search.SearchResponse)2 Suggest (org.opensearch.search.suggest.Suggest)2 PhraseSuggestionBuilder (org.opensearch.search.suggest.phrase.PhraseSuggestionBuilder)2 TermSuggestion (org.opensearch.search.suggest.term.TermSuggestion)2 IOException (java.io.IOException)1 BulkRequest (org.opensearch.action.bulk.BulkRequest)1 BulkResponse (org.opensearch.action.bulk.BulkResponse)1 IndexRequest (org.opensearch.action.index.IndexRequest)1 RestHighLevelClient (org.opensearch.client.RestHighLevelClient)1 CreateIndexRequest (org.opensearch.client.indices.CreateIndexRequest)1 XContentParser (org.opensearch.common.xcontent.XContentParser)1 MatchNoneQueryBuilder (org.opensearch.index.query.MatchNoneQueryBuilder)1 QueryBuilder (org.opensearch.index.query.QueryBuilder)1 TermQueryBuilder (org.opensearch.index.query.TermQueryBuilder)1