ElasticSearch completion suggester with Java API

前端 未结 2 1877
天命终不由人
天命终不由人 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 09:52

    In order to use completion feature, you need to dedicate one field, which will be called completion and you have to specify a special mapping for it.

    For example:

    "mappings": {
       "article": {
         "properties": {
          "content": {
            "type": "string"
          },
         "completion_suggest": {
          "type": "completion"}
         }
       }
    }
    

    The completion_suggest field is the field we will use for the autocomplete function in the above code sample. After this mapping defination, the data must be indexing as follow:

    curl -XPOST localhost:9200/kodcucom/article/1 -d '{
       "content": "elasticsearch",
       "completion_suggest": {
         "input": [ "es", "elastic", "elasticsearch" ],
         "output": "ElasticSearch"
       }
    }'
    

    Then Java API can be used as follows for get suggestions:

    CompletionSuggestionBuilder skillNameSuggest  = new CompletionSuggestionBuilder("complete");
    skillNameSuggest.text("es");
    skillNameSuggest.field("completion_suggest");
    
    SearchResponse searchResponse = client.prepareSearch("kodcucom")
            .setTypes("article")
            .setQuery(QueryBuilders.matchAllQuery())
            .addSuggestion(skillNameSuggest)
            .execute().actionGet();
    
    CompletionSuggestion compSuggestion = searchResponse.getSuggest().getSuggestion("complete");
    
    List<CompletionSuggestion.Entry> entryList = compSuggestion.getEntries();
    if(entryList != null) {
        CompletionSuggestion.Entry entry = entryList.get(0);
        List<CompletionSuggestion.Entry.Option> options =entry.getOptions();
        if(options != null)  {
            CompletionSuggestion.Entry.Option option = options.get(0);
            System.out.println(option.getText().string());
        }
    }
    
    0 讨论(0)
  • 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<String,Object> suggestionMap = new HashMap<>();
            suggestionsExtractor.execute(new ActionListener<SearchResponse>() {
                @Override
                public void onResponse(SearchResponse searchResponse) {
                   if(searchResponse.status().equals(RestStatus.OK)) {
                       searchResponse.getSuggest().getSuggestion("productsearch").getEntries().forEach(e -> {
                           e.getOptions().forEach(s -> {
                               ArrayList<Object> 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;
        }
    
    0 讨论(0)
提交回复
热议问题