Search code examples
elasticsearchspring-data-elasticsearchelasticsearch-java-api

How can I make phrase suggester query with Elasticsearch java api?


I am using 7.10. version of elasticsearch. I created an index and did settings-mappings. Then I sent query to index by using http requests. I got the results I need, but I want to do same thing with Java API. However, I couldn't. Can you help me to send request and get the result as list in java from scratch ?

And here it is my query that I used for obtain suggestions:

{
  "suggest": {
    "text": "some title I want to search",
    "phrase_suggester": {
      "phrase": {
        "field": "title.shingle",
                "max_errors": 2,
                "size": 5,
                "confidence": 0.0,
                "direct_generator": [{
                    "field": "title.shingle",
                    "max_edits": 2
          }
        ]
      }
    }
  }
}

How can I write this query with Elasticsearch Java API. Can you help me figure this out ?


Solution

  • Finaly I've found my own answers. It was so hard to find the solution due to lack of documents about these kind of specific topics. I'm sharing my solution for those who wondered:

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    
    PhraseSuggestionBuilder builder = SuggestBuilders.phraseSuggestion("title.shingle")
                    .addCandidateGenerator(new DirectCandidateGeneratorBuilder("title.shingle")
                            .suggestMode("always"))
                    .text(query)
                    .maxErrors(2f)
                    .confidence(0f);
    
            SuggestBuilder suggestBuilder = new SuggestBuilder().addSuggestion("suggestion", builder);
            searchSourceBuilder.suggest(suggestBuilder);
    
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("index_name");
            searchRequest.source(searchSourceBuilder);
    
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);