SolrJ
(1) 引入相关依赖
org.apache.solr solr-solrj
(2) 编写配置文件:applicationContext-solr.xml
(3) 导入数据到solr索引库
@Servicepublic class SearchItemServiceImpl implements SearchItemService { @Autowired private SearchItemMapper searchItemMapper; @Autowired private SolrServer solrServer; public Result importItemsToIndex() { try { ListitemList = searchItemMapper.getItemList(); for (SearchPojo searchPojo : itemList) { SolrInputDocument document = new SolrInputDocument(); document.addField("id", searchPojo.getId()); document.addField("item_title", searchPojo.getTitle()); document.addField("item_sell_point", searchPojo.getSell_point()); document.addField("item_price", searchPojo.getPrice()); document.addField("item_image", searchPojo.getImage()); document.addField("item_desc", searchPojo.getItem_desc()); document.addField("item_category_name", searchPojo.getCategory_name()); solrServer.add(document); } solrServer.commit(); } catch (Exception e) { e.printStackTrace(); return Result.build(500, "索引库导入失败!"); } return Result.ok(); }}
(4) 搜索solr索引库
@Servicepublic class SearchServiceImpl implements SearchService { @Autowired private SearchDao searchDao; public SearchResult search(String queryString, int page, int rows) throws Exception { SolrQuery query = new SolrQuery(queryString); if (page < 1) { page = 1; } if (rows < 1) { rows = 10; } query.setStart((page - 1) * rows); query.setRows(rows); // 设置默认搜索域 query.set("df", "item_title"); // 设置高亮 query.setHighlight(true); // 开启高亮 query.addHighlightField("item_title"); // 显示高亮的域 query.setHighlightSimplePre(""); //设置高亮颜色 query.setHighlightSimplePost(""); SearchResult result = searchDao.search(query); // 计算总页数 long recordCount = result.getRecordCount(); long pages = recordCount / rows; if (recordCount % rows > 0) { pages++; } result.setTotalPages(pages); return result; }}