0

The documentation says nothing on how to use the new suggest api with Java Api client (not the high level rest client). The index is very simple. Here is the mapping

{
  "mappings": {
      "properties": {
        "name": {
          "type": "completion",
          "contexts": [
            {
              "name": "place_type",
              "type": "category"
            }
          ]
        },
        "entityId": {
          "type": "keyword"
        }
      }
    
  }
}

I am using a basic prefix with context filtering

{
  "suggest": {
    "place_suggestion": {
      "prefix": "oli",
      "completion": {
        "field": "name",
        "size": 10,
        "contexts": {
          "place_type": [ "d2c" ]
        }
      }
    }
  }
}

Can anyone help me with the java code snippet for the same search query. Elastic client version : 7.17.6 Using the following elastic client : https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/7.17/connecting.html

1 Answer 1

2

Try this code:

Map<String, List<CompletionContext>> mapContext = new HashMap<>();
    mapContext.put("place_type", List.of(CompletionContext.of(cc -> cc.context(ctx -> ctx.category("d2c")))));

Map<String, FieldSuggester> map = new HashMap<>();
map.put("place_suggestion", FieldSuggester.of(fs -> fs
    .completion(cs -> cs.skipDuplicates(true)
        .size(5)
        .field("name")
        .contexts(mapContext)
    )
));

Suggester suggester = Suggester.of(s -> s
    .suggesters(map)
    .text("oli")
);

var response = client.search(s ->
        s.index("idx_test")
            .suggest(suggester)
    , Void.class);

var suggestions = response.suggest().get("place_suggestion");

for (var suggest : suggestions) {
  for (var option : suggest.completion().options()) {
    System.out.println("suggestion: " + option.text());
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering @rabbitbr. The pojo you have used in response "MovieSuggest" can you share the structure of that? does elastic api also provide full response pojo because I beleive this is something standard so why do we need to create our pojo from scratch? and if we need then what are the mandatory varaible we should keep in it?

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.