ElasticSearch completion suggester with Java API

前端 未结 2 1876
天命终不由人
天命终不由人 2021-01-21 09:12

I had tried a few example codes on suggester feature of ElasticSearch on the net but I couldn\'t solve my problem against the autocomplete solution

my index:

<         


        
2条回答
  •  北海茫月
    2021-01-21 10:07

    Following link provides you the details of how to create a suggester index. https://www.elastic.co/blog/you-complete-me

    Now, I use asynchronous Suggestionbuilder Java API to generate suggestions based on terms.

     SearchRequestBuilder suggestionsExtractor = elasticsearchService.suggestionsExtractor("yourIndexName", "yourIndexType//not necessary", "name_suggest", term);
            System.out.println(suggestionsExtractor);
            Map suggestionMap = new HashMap<>();
            suggestionsExtractor.execute(new ActionListener() {
                @Override
                public void onResponse(SearchResponse searchResponse) {
                   if(searchResponse.status().equals(RestStatus.OK)) {
                       searchResponse.getSuggest().getSuggestion("productsearch").getEntries().forEach(e -> {
                           e.getOptions().forEach(s -> {
                               ArrayList contents = new ArrayList<>();
    
                               suggestionMap.put(s.getText().string(), s.getScore());
    
                           });
                       });
    
    
                   }
    
                }
    
                @Override
                public void onFailure(Exception e) {
                    Helper.sendErrorResponse(routingContext,new JsonObject().put("details","internal server error"));
                    e.printStackTrace();
                }
            });
    
    
    

    Following is how suggestionbuilder is created.

    public SearchRequestBuilder suggestionsExtractor(String indexName, String typeName, String field, String term) {
    
            CompletionSuggestionBuilder csb = SuggestBuilders.completionSuggestion(field).text(term);
            SearchRequestBuilder suggestBuilder = client.prepareSearch()
                    .suggest(new SuggestBuilder().addSuggestion(indexName, csb));
            return suggestBuilder;
        }
    

    提交回复
    热议问题