简体   繁体   English

使用Java API的ElasticSearch完成建议器

[英]ElasticSearch completion suggester with Java API

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 我在网上尝试了一些关于ElasticSearch的建议功能的示例代码但是我无法解决我对自动完成解决方案的问题

my index: 我的索引:

client.prepareIndex("kodcucom", "article", "1")
      .setSource(putJsonDocument("ElasticSearch: Java",
        "ElasticSeach provides Java API, thus it executes all operations " +
        "asynchronously by using client object..",
         new Date(),
         new String[]{"elasticsearch"},
         "Hüseyin Akdoğan")).execute().actionGet();

and I used suggestbuilder to obtain the keyword then scan through the content "field", and here is where the null pointer exception occurs due to no result 我使用了suggestbuilder来获取关键字,然后浏览内容“field”,这里是由于没有结果而发生空指针异常的地方

CompletionSuggestionBuilder skillNameSuggest = new CompletionSuggestionBuilder("skillNameSuggest");

skillNameSuggest.text("lien");
skillNameSuggest.field("content");

SuggestRequestBuilder suggestRequestBuilder = client.prepareSuggest("kodcucom").addSuggestion(skillNameSuggest);

SuggestResponse suggestResponse = suggestRequestBuilder.execute().actionGet();

Iterator<? extends Suggest.Suggestion.Entry.Option> iterator =
          suggestResponse.getSuggest().getSuggestion("skillNameSuggest").iterator().next().getOptions().iterator();

Am I missing some filters or input criteria in order to get result? 我是否缺少一些过滤器或输入标准才能获得结果? Any result should ok such as autocomplete or record found. 任何结果都应该可以,例如自动完成或找到记录。

EDIT 1: 编辑1:

This is where I got the NPE and I could see that none of any result return at suggestResponse from debug mode 这是我获得NPE的地方,我可以看到没有任何结果从suggestResponse返回调试模式

Iterator<? extends Suggest.Suggestion.Entry.Option> iterator =
              suggestResponse.getSuggest().getSuggestion("skillNameSuggest").iterator().next().getOptions().iterator();

EDIT 2: I am using 2.1.1 version of ElasticSearch Java API 编辑2:我使用的是2.1.1版本的ElasticSearch Java API

EDIT 3: I tried in splitting up the iterator line into several code blocks, the NPE occur at the last line when converting a set of data into iterator, but there is not much helping 编辑3:我试图将迭代器行拆分成几个代码块,当将一组数据转换为迭代器时,NPE出现在最后一行,但没有太多帮助

Suggest tempSuggest = suggestResponse.getSuggest();

Suggestion tempSuggestion = tempSuggest.getSuggestion("skillNameSuggest");

Iterator tempIterator = tempSuggestion.iterator();

I see that the codes: 我看到代码:

SuggestRequestBuilder suggestRequestBuilder = client.prepareSuggest("kodcucom").addSuggestion(skillNameSuggest);

    SuggestResponse suggestResponse = suggestRequestBuilder.execute().actionGet();

has already consists a empty array/dataset, am I using the suggest request builder incorrectly? 已经包含一个空数组/数据集,我是否错误地使用了建议请求构建器?

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. completion_suggest字段是我们将用于上述代码示例中的自动完成功能的字段。 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: 然后可以使用Java API获取建议:

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());
    }
}

Following link provides you the details of how to create a suggester index. 以下链接为您提供了有关如何创建建议者索引的详细信息。 https://www.elastic.co/blog/you-complete-me https://www.elastic.co/blog/you-complete-me

Now, I use asynchronous Suggestionbuilder Java API to generate suggestions based on terms. 现在,我使用异步Suggestionbuilder Java API根据术语生成建议。

 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. 以下是如何创建suggestionbuilder。

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM