1、介绍
Solr从1.4开始便提供了检查建议,检索建议目前是各大搜索的标配应用,主要作用是避免用户输入错误的搜索词,同时将用户引导到相应的关键词搜索上。通常,我们将其称为搜索联想。
其效果如图所示。在Solr中,实现该功能的模块叫做suggest。
2、配置
配置manage-schema
配置solrconfig.xml
text_spell suggest org.apache.solr.spelling.suggest.Suggester org.apache.solr.spelling.suggest.tst.TSTLookup suggestion 0.0001 spellchecker freq true true suggest true false 10 true suggest
3、重启solr,索引数据
4、效果预览
5、java代码查询
private static void getSuggest(String message) throws SolrServerException, IOException{ SolrQuery params = new SolrQuery(); params.set("qt", "/suggest");// params.setQuery("中国"); params.setQuery(message); QueryResponse response = null; response = solr.query(params); String suggest = response.toString(); suggest = suggest.replace("=",":"); System.out.println(suggest); JSONObject obj = new JSONObject(suggest); StackstObj = new Stack (); stObj.push(obj); Map resultMap =new HashMap (); JsonToMap(stObj,resultMap); if(resultMap.containsKey("suggestion")){ System.out.println("suggestion:"+resultMap.get("suggestion")); } } /** * @Author:sks * @Description:把json对象数据存储在map以键值对的形式存储,只存储叶节点 * @Date: */ private static void JsonToMap(Stack stObj,Map resultMap) throws SolrServerException, IOException{ if(stObj == null && stObj.pop() == null){ return ; } JSONObject json = stObj.pop(); Iterator it = json.keys(); while(it.hasNext()){ String key = (String) it.next(); //得到value的值 Object value = json.get(key); //System.out.println(value); if(value instanceof JSONObject) { stObj.push((JSONObject)value); //递归遍历 JsonToMap(stObj,resultMap); } else { resultMap.put(key, value); } } }