当前位置: 首页 > elasticsearch, 搜索 > 正文

elasticsearch SuggestionBuilder应用实例

1 星2 星3 星4 星5 星 (2 次投票, 评分: 5.00, 总分: 5)
Loading ... Loading ...
baidu_share

我们再使用solr时,可以用spellchecker进行搜索时建议。在elasticsearch中我们使用SuggestionBuilder进行拼写建议。
1.使用TermSuggestionBuilder

TermSuggestionBuilder suggest=new TermSuggestionBuilder("my-suggest-1");
            	suggest.analyzer("ik").field("content").size(n).text(q).maxTermFreq(10).minDocFreq(0).suggestMode("always");
            	Client client = ESServiceSingleton2.getTransportClient();
            	SearchResponse response = client.prepareSearch("cms")
            			.setTypes("news").setSearchType(SearchType.COUNT)
            			.setSuggestText(q)
            			.addSuggestion(suggest)
            			.execute().actionGet();
            	Suggest suggest=response.getSuggest();
List<? extends Entry<? extends Option>>  list=suggest.getSuggestion("simple").getEntries();
            	for(int i=0; i<list.size();i++){
 
            		List<?> options=list.get(i).getOptions();
            		for(int j=0;j<options.size();j++){
            			if(options.get(j) instanceof Option){
            				Option op=(Option)options.get(j);
            				System.out.println(op.getScore());
            				System.out.println(op.getText());
 
            			}
 
            		}
            		System.out.println(list.get(i).getText());
            	}

1.使用PhraseSuggestionBuilder

//q为查询词
//n为返回建议词条长度
Suggest suggest = searchSuggest(client, q,
                        phraseSuggestion("simple").maxErrors(0.5f).field("content").analyzer("ik")
                          .addCandidateGenerator(PhraseSuggestionBuilder.candidateGenerator("content").minWordLength(1).suggestMode("always"))
                                .size(n));
 
   SearchResponse response = client.prepareSearch("cms")
            			.setTypes("news").setSearchType(SearchType.COUNT)
            			.setSuggestText(q)
            			.addSuggestion(suggest)
            			.execute().actionGet();
            	Suggest suggest=response.getSuggest();
List<? extends Entry<? extends Option>>  list=suggest.getSuggestion("simple").getEntries();
            	for(int i=0; i<list.size();i++){
 
            		List<?> options=list.get(i).getOptions();
            		for(int j=0;j<options.size();j++){
            			if(options.get(j) instanceof Option){
            				Option op=(Option)options.get(j);
            				System.out.println(op.getScore());
            				System.out.println(op.getText());
 
            			}
 
            		}
            		System.out.println(list.get(i).getText());
            	}

经过测试,发现效果不是很好。建议大家使用elasticsearch-suggest-plugin
参考文章:
http://www.elasticsearch.org/guide/reference/api/search/suggest/

本文固定链接: http://www.chepoo.com/elasticsearch-suggestion-builder-apply-demo.html | IT技术精华网

elasticsearch SuggestionBuilder应用实例:等您坐沙发呢!

发表评论