1

How do I make a query like this:

{
  "suggest": {
    "my_index_suggest": {
      "prefix": value,
      "completion": {
        "field": "suggest_field",
        "fuzzy": {
          "fuzziness" : 1
        },
        "size": 5
      }
    }
  }
}

with Java High Level Rest Client? I am not sure if I should use the SuggestionBuilder or the QueryBuilder.

What is accomplished in a minute in JS or Python is once again an adventure in Java 😪

1 Answer 1

2

Ok, here is my own solution:

public List<String> getSuggestion(String input) throws IOException {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    SuggestionBuilder termSuggestionBuilder = SuggestBuilders.completionSuggestion("my_index_suggest").text(input);

    SuggestBuilder suggestBuilder = new SuggestBuilder();
    suggestBuilder.addSuggestion("suggest_field", termSuggestionBuilder);
    searchSourceBuilder.suggest(suggestBuilder);

    SearchRequest searchRequest = new SearchRequest();
    searchRequest.source(searchSourceBuilder);

    SearchResponse searchResponse = suggestionIndexClient.search(searchRequest, RequestOptions.DEFAULT);
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(searchResponse.getSuggest().iterator(), Spliterator.ORDERED), false)
            .flatMap(suggestion -> suggestion.getEntries().get(0).getOptions().stream())
            .map((Suggest.Suggestion.Entry.Option option) -> option.getText().toString())
            .collect(Collectors.toList());
}

If you don't like Streams, feel free to use this Suggestion generic monstrosity plus the while-loop nobody asked for:

    Iterator<Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>>> iterator = searchResponse.getSuggest().iterator();
    Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestion;

    List<String> resultList = null;
    while (iterator.hasNext()) {
        suggestion = iterator.next();
        resultList = fn.getEntries().get(0).getOptions().stream()
            .map((Suggest.Suggestion.Entry.Option option) -> option.getText().toString())
            .collect(Collectors.toList());
    }

    return resultList;
Sign up to request clarification or add additional context in comments.

1 Comment

how to add custom fuzziness param to suggestion query?? I'm unable to find it for 7.xx series Java rest high level client

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.