前期准备
搭建solr服务
参考上一篇,搭建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; } }
前端示例
其它的根据业务需求具体扩展吧,在前端可以对查询到的数据进行一些自定义展示(关键字标红高亮,每条记录分类,点击跳转到记录详情页面)。
时间: 2024-10-18 03:05:32