Retrieve documents from Completion Suggester using Elasticsearch Java API

When I execute completion suggester request using curl, in the response I can find also the documents

curl -X GET 'localhost:9200/shop/_search?pretty&size=20' -H 'Content-Type: application/json' -d'{
    "suggest": {
        "product-suggest" : {
            "prefix" : "phone",
            "completion" : {
                "field" : "title",
                "skip_duplicates": true
            }
        }
    }
}'

the response

{
  "took" : 15,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "suggest" : {
    "product-suggest" : [
      {
        "text" : "phone",
        "offset" : 0,
        "length" : 12,
        "options" : [
          {
            "text" : "Phone",
            "_index" : "shop",
            "_type" : "_doc",
            "_id" : "a02fd264-c25c-4634-8bd9-e275a293ce1d",
            "_score" : 1.0,
            "_source" : {
              "title" : "Phone",
              "price" : 219.99
            }
          }
        ]
      }
    ]
  }
}


So, in the response I can find the document in the "_source" field.

Using Java API

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.suggest(new SuggestBuilder()
                .addSuggestion("product-suggest",
                        new CompletionSuggestionBuilder("title").prefix("phone").skipDuplicates(true)));
        searchRequest.source(searchSourceBuilder);

SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

searchResponse.getSuggest().getSuggestion("search").getEntries().get(0).getOptions(.get(0).getText();

So, I can find the method to retrieve the text getText, but there are no method to retrieve the source.

Is there some way to retrieve the source?

You need to type cast suggestion to CompletionSuggestion.

String s = ((CompletionSuggestion)searchResponse.getSuggest().getSuggestion("product-suggest")).getOptions().get(0).getHit().getSourceAsString();
        
System.out.println(s);

Thank you.

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