Using CompletionSuggestionBuilder with context in Java (Re-post)

(Re-posting this as it was automatically closed due to lack of replies)

Hi guys

I'm trying to use the CompletionSuggestionBuilder (context suggester) with the Java client (ES 5.0.1), and I'm struggling with adding contexts, and the API is not entirely clear on that.

This is as far as I got, but again, only by intuitively surfing the API, not really sure if this is the right way to go about it, as documentation is scarce in this area.

CompletionSuggestionBuilder completion = new CompletionSuggestionBuilder(FIELD_SUGGEST)
Map<String, List<? extends ToXContent>> contexts = new HashMap<>();

Also, methods on CompletionSuggestionBuilder.Contexts2x seem to be all deprecated, which I presume is not the route to pursue.


I have a working sample below from the JAVA client for ES 2.4.2 - Not sure, if you requires any changes, but if so it will be minimal.

Be aware to change names appropriately - And remember, that the completion suggester only works on data loaded into the index previously.

    public Set<KeywordSuggest> keywordSuggester(String suggestText) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectReader payloadReader = objectMapper.readerFor(KeywordPayload.class);

        Set<KeywordSuggest> suggestSet = new TreeSet<>();
        final SuggestRequestBuilder suggestRequestBuilder = this.esClient.prepareSuggest();
        CompletionSuggestionBuilder completionSuggestionBuilder = new CompletionSuggestionBuilder("keyword");
        final SuggestResponse suggestResponse = suggestRequestBuilder.execute().actionGet();
        final Suggest suggest = suggestResponse.getSuggest();
        final Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestion = suggest.getSuggestion("keyword");
        final Iterator<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> iterator = suggestion.iterator();
        while(iterator.hasNext()) {
            final Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> entry =;
            final List<? extends Suggest.Suggestion.Entry.Option> options = entry.getOptions();
            final Iterator<? extends Suggest.Suggestion.Entry.Option> optionsIterator = options.iterator();
            while(optionsIterator.hasNext()) {
                final Suggest.Suggestion.Entry.Option next =;
                final CompletionSuggestion.Entry.Option completion = (CompletionSuggestion.Entry.Option) next;
                final Text text = completion.getText();
                KeywordPayload keywordPayload = payloadReader.readValue(completion.getPayloadAsString());
                KeywordSuggest keywordSuggest = new KeywordSuggest();
        return suggestSet;

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.