use of org.opensearch.search.suggest.SuggestionBuilder 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());
}
}
}
Aggregations