Home > Blockchain >  How do we use suggest api for Query using Java api client in elasticsearch?
How do we use suggest api for Query using Java api client in elasticsearch?

Time:12-20

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

CodePudding user response:

Try this code:

Map<String, List> 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());
  }
}
  • Related