solrconfig.xml
配置
<searchComponent class="solr.SpellCheckComponent" name="suggest">
<lst name="spellchecker">
<str name="name">suggest</str>
<str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
<str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookupFactory</str>
<str name="field">product_name</str>
<!-- the indexed field to derive suggestions from -->
<float name="threshold">0.005</float>
<str name="sourceLocation">suggest_dict.txt</str>
<str name="buildOnCommit">true</str>
</lst>
</searchComponent>
<requestHandler class="org.apache.solr.handler.component.SearchHandler"
name="/suggest">
<lst name="defaults">
<str name="spellcheck">true</str>
<str name="spellcheck.dictionary">suggest</str>
<str name="spellcheck.onlyMorePopular">true</str>
<str name="spellcheck.count">10</str>
<str name="spellcheck.collate">true</str>
</lst>
<arr name="components">
<str>suggest</str>
</arr>
</requestHandler>
sourceLocation 没有值就会去找 name=”field”
具体值参考:https://cwiki.apache.org/confluence/display/solr/Suggester
导入:
public String initSuggest() {
List<ProductEntity> prodList = this.getAll();
if (prodList != null && prodList.size() > 0) {
StringBuffer buffer = new StringBuffer();
for (ProductEntity productEntity : prodList) {
buffer.append(productEntity.getName()).append("\n");
}
if (buffer.length() < 1) {
return null;
}
try {
File file = new File(this.suggestPath);
FileUtils.write(file, buffer.toString(), "UTF-8");
this.logger.error("suggest字典生成成功");
return buffer.toString();
} catch (Exception e) {
this.logger.error("定时生成solr智能提示所需文档失败");
e.printStackTrace();
}
}
return null;
}
查询:
public static List<String> suggest(String url, String queryValue) throws Exception {
HttpSolrClient server = getServer(url);
List<String> results = new ArrayList<>();
SolrQuery solrQuery = new SolrQuery();
solrQuery.set("qt", "/suggest");
solrQuery.set("q", queryValue);
QueryResponse queryResponse = server.query(solrQuery);
SpellCheckResponse spellCheckResponse = queryResponse
.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<Suggestion> suggestionList = spellCheckResponse.getSuggestions();
for (Suggestion suggestion : suggestionList) {
List<String> suggestedWordList = suggestion.getAlternatives();
for (String word : suggestedWordList) {
results.add(word);
}
}
}
return results;
}