我已经在网上尝试了一些有关ElasticSearch的提示功能的示例代码,但是无法针对自动完成解决方案解决我的问题
我的索引:
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();
我使用了suggestbuilder来获取关键字,然后扫描内容“字段”,这是由于没有结果而导致空指针异常的地方
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();
我是否缺少一些过滤器或输入条件以获取结果?任何结果都应该可以,例如自动完成或找到记录。
编辑1:
这是我得到NPE的地方,我可以看到suggestResponse 调试模式下没有任何结果返回
suggestResponse
Iterator<? extends Suggest.Suggestion.Entry.Option> iterator = suggestResponse.getSuggest().getSuggestion("skillNameSuggest").iterator().next().getOptions().iterator();
编辑2: 我正在使用2.1.1版本的ElasticSearch Java API
编辑3: 我试图将迭代器行拆分为几个代码块,将一组数据转换为迭代器时,NPE出现在最后一行,但是没有太多帮助
Suggest tempSuggest = suggestResponse.getSuggest(); Suggestion tempSuggestion = tempSuggest.getSuggestion("skillNameSuggest"); Iterator tempIterator = tempSuggestion.iterator();
我看到的代码:
SuggestRequestBuilder suggestRequestBuilder = client.prepareSuggest("kodcucom").addSuggestion(skillNameSuggest); SuggestResponse suggestResponse = suggestRequestBuilder.execute().actionGet();
已经包含一个空数组/数据集,我使用建议请求构建器的方式不正确吗?
为了使用完成功能,您需要专用一个字段,该字段将被称为完成,并且必须为其指定特殊的映射。
例如:
"mappings": { "article": { "properties": { "content": { "type": "string" }, "completion_suggest": { "type": "completion"} } } }
complete_suggest字段是上面代码示例中将用于自动完成功能的字段。在此映射定义之后,必须按如下所示索引数据:
curl -XPOST localhost:9200/kodcucom/article/1 -d '{ "content": "elasticsearch", "completion_suggest": { "input": [ "es", "elastic", "elasticsearch" ], "output": "ElasticSearch" } }'
然后可以如下使用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()); } }