通过SolrJ获取Solr检索结果
1、通过SolrParams的方式提交查询参数
SolrClient solr = new HttpSolrClient("http://localhost:8080/solr/core"); Map<String, String> map = new HashMap<String, String>(); keyword = "".equals(keyword) ? "*" : keyword; map.put("q", "search_item:" + keyword); map.put("indent", "true"); map.put("hl", "true"); map.put("hl.fl", "title, summary"); map.put("hl.simple.pre", "<font color=\"red\">"); map.put("hl.simple.post", "</font>"); map.put("start", "0"); map.put("rows", "10"); SolrParams params = new MapSolrParams(map); try { QueryResponse resp = solr.query(params); Map<String, Map<String, java.util.List<String>>> highlight = resp.getHighlighting();//高亮集合 SolrDocumentList docsList = resp.getResults();//文档集合 int docNumFound = (int) docsList.getNumFound();//文档数 ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); String key = ""; Map<String, String> docMap; for (SolrDocument doc : docsList) { docMap = new HashMap<String, String>(); key = doc.get("id").toString(); if(key != null && highlight.get(key) != null){ docMap.put("id", key); docMap.put("type", doc.get("type").toString()); String title = (String) (!"*".equals(keyword) && highlight.get(key).get("title") != null ? highlight.get(key).get("title").get(0) : doc.get("title")); docMap.put("title", title); String summary = (String) (!"*".equals(keyword) && highlight.get(key).get("summary") != null ? highlight.get(key).get("summary").get(0) : doc.get("summary")); docMap.put("summary", summary); } list.add(docMap); } solr.close(); } catch (Exception e) { e.printStackTrace(); }finally{ if (solr != null) { try { solr.close(); } catch (IOException e) { e.printStackTrace(); } } }
2、通过SolrQuery提交参数
SolrClient solr = new HttpSolrClient("http://localhost:8080/solr/core"); SolrQuery query = new SolrQuery(); //设置高亮 query.setQuery("name:datou"); query.setHighlight(true); // 开启高亮组件或用query.setParam("hl", "true"); query.addHighlightField("name");// 高亮字段 query.setHighlightSimplePre("<font color='red'>");//标记,高亮关键字前缀 query.setHighlightSimplePost("</font>");//后缀 // query.setHighlightSnippets(1);//结果分片数,默认为1 // query.setHighlightFragsize(1000);//每个分片的最大长度,默认为100 System.out.println(query);//用于调试程序 QueryResponse rsp = solr.query(query); NamedList list = (NamedList) rsp.getResponse().get("highlighting"); System.out.println(list);//用于显示list中的值 for (int i = 0; i < list.size(); i++){ System.out.println("id=" + list.getName(i) + "文档中高亮显示的字段:" + list.getVal(i)); }
本文转自秋楓博客园博客,原文链接:http://www.cnblogs.com/rwxwsblog/p/5059144.html,如需转载请自行联系原作者