3

I am working on ES5 through java, and am trying to add context to a CompletionSuggestionBuilder. I have a map of String objects that need to be added. The code I have so far is -

Map<String, String> context = ...
CompletionSuggestionBuilder csb = SuggestBuilders.completionSuggestion(field).text(value).size(count);

How do I add context objects to csb? I think the method to use is -

csb.contexts(Map<String, List<? extends ToXContent>> queryContexts)

But I don't know how to get from my map to the map to pass as arguments to the contexts method.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user2689782
  • 747
  • 14
  • 31

1 Answers1

11

You can create Map<String, List<? extends ToXContent>> like this;

Collections.singletonMap("cat", Arrays.asList(CategoryQueryContext.builder().setCategory("cat0").setBoost(3).build(), CategoryQueryContext.builder().setCategory("cat1").build()))

I think currently supported types that extend ToXContext are CategoryQueryContext and GeoQueryContext

The strange thing here is that if I create a local variable and pass it to the contexts it does not work. So, I just passed it directly to the contexts it does work.

Full example would be like this:

CompletionSuggestionBuilder prefix = SuggestBuilders.completionSuggestion(FIELD).prefix("sugg").contexts(Collections.singletonMap("cat", Arrays.asList(CategoryQueryContext.builder().setCategory("cat0").setBoost(3).build(), CategoryQueryContext.builder().setCategory("cat1").build())));

It is all written in their test cases. You can take a look at it: https://github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/search/suggest/ContextCompletionSuggestSearchIT.java#L290

Hope it helps.

endertunc
  • 1,989
  • 2
  • 21
  • 31
  • Thanks for this. As an FYI, if you want it to work with a local variable (i.e. without getting shouted at by Java generic checks), you need to do: `final Map> contexts = ...` – Tristan Perry May 21 '20 at 10:45