參考上一篇,搭建solr搜索服務。
maven工程的話,添加如下依賴,
<!-- https://mvnrepository.com/artifact/org.apache.solr/solr-solrj --> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>5.5.3</version> </dependency>
也可以自己導入jar包
在solr安裝目錄下,找到solr-5.5.3\dist\solrj-lib路徑,添加裡面所有的jar包到自己的工程,別忘了在外面的文件夾還有個solr-solrj-5.5.3.jar包,一起拷貝。
這裡簡單給個示例(包含分頁),Spring mvc工程的:
@ResponseBody @RequestMapping(value = "/searchByKeyWord", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json; charset=utf-8") public String search(HttpServletRequest request, HttpServletResponse response, String keyWord, int pageSize, int pageOffset) { try { String urlString = ConfigUtil.getValueByKey("solrServiceUrl"); SolrClient solr = new HttpSolrClient(urlString); SolrQuery query = new SolrQuery(); query.set("q", URLDecoder.decode(keyWord, "UTF-8")); query.set("start", String.valueOf(pageOffset * pageSize)); query.set("rows", String.valueOf(pageSize)); QueryResponse queryResponse = solr.query(query); // SolrDocumentList list = queryResponse.getResults(); Map<String, Object> result = new HashMap<String, Object>(); List<OCSearchObject> rstList = queryResponse.getBeans(OCSearchObject.class); result.put("success", true); result.put("key", URLDecoder.decode(keyWord, "UTF-8")); result.put("list", rstList); result.put("totalCount", queryResponse.getResults().getNumFound()); solr.close(); return json(result); } catch (Exception e) { LOGGER.error(e.toString(), e); return jsonpFalse(request, response, "code_error"); } }
以下是OCSearchObject類,注意要與data-config.xml配置的字段對應起來,還有就是不要忘了在字段前面加上@Field注解(org.apache.solr.client.solrj.beans.Field)。
public class OCSearchObject { private Long id; private String name; private String fullText; private String type; /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ @Field("id") public void setId(Long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ @Field("name") public void setName(String name) { this.name = name; } /** * @return the fullText */ public String getFullText() { return fullText; } /** * @param fullText the fullText to set */ @Field("fullText") public void setFullText(String fullText) { this.fullText = fullText; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ @Field("type") public void setType(String type) { this.type = type; } }
其它的根據業務需求具體擴展吧,在前端可以對查詢到的數據進行一些自定義展示(關鍵字標紅高亮,每條記錄分類,點擊跳轉到記錄詳情頁面)。