Spring集成Solr搜索引擎

1、导入jar包

org.apache.solr
solr-solrj
4.10.2


commons-logging
commons-logging
1.1

2、Spring配置文件中定义solr的bean












3、Service中注入solr的bean
@Service
@Qualifier("goodsService")
public class GoodsServiceImpl implements GoodsService {
private Logger log = Logger.getLogger(GoodsServiceImpl.class);
@Resource
@Qualifier("solrServer")
private SolrServer solrServer;
4、实现solr查询
public List queryGoodsList(GoodsQuery goodsQuery) throws SolrServerException {
SolrQuery solrQuery = new SolrQuery();
//设置关键字
solrQuery.setQuery(goodsQuery.getName());
//设置默认检索域
solrQuery.set("df", "name");
// 分页
// solrQuery.setStart(0);
// solrQuery.setRows(5);
// 只查询指定域
solrQuery.set("fl", "id,name,goods_price,goods_status,goods_type,goods_img,goods_describle");
// 设置高亮
solrQuery.setHighlight(true);
// 指定高亮域
solrQuery.addHighlightField("name");
// 前缀
solrQuery.setHighlightSimplePre("");
solrQuery.setHighlightSimplePost("
");
// 执行查询
QueryResponse response = solrServer.query(solrQuery);
// 文档结果集
SolrDocumentList docs = response.getResults();
Map>> highlighting = response.getHighlighting();
List goodsList = new ArrayList();
for (SolrDocument doc : docs) {
TGoods goods = new TGoods();
goods.setId(Integer.parseInt(doc.get("id").toString()));
goods.setPrice(Double.parseDouble(doc.get("goods_price").toString()));
goods.setStatus(Integer.parseInt(doc.get("goods_status").toString()));
goods.setType(Integer.parseInt(doc.get("goods_type").toString()));
goods.setImg((String)doc.get("goods_img"));
goods.setDescrible((String)doc.get("goods_describle"));
Map> map = highlighting.get((String) doc.get("id"));
List list = map.get("name");
goods.setName(list.get(0));
goodsList.add(goods);
}
return goodsList;
}
4、solr实现添加
public void saveGoods(TGoods goods) throws SolrServerException, IOException {
//创建新的文档对象
SolrInputDocument solrInputDocument = new SolrInputDocument();
//设置文档的域
solrInputDocument.setField("id", goods.getId());
solrInputDocument.setField("name", goods.getName());
solrInputDocument.setField("goods_price", goods.getPrice());
solrInputDocument.setField("goods_status", goods.getStatus());
solrInputDocument.setField("goods_type", goods.getType());
solrInputDocument.setField("goods_img", goods.getImg());
solrInputDocument.setField("goods_describle", goods.getDescrible());
//进行添加
solrServer.add(solrInputDocument);
//进行手动提交,否则无法进行添加
solrServer.commit();
}
5、solr实现删除
public void deleteGoodsById(Integer id) throws SolrServerException, IOException {
log.debug("*********deleteGoodsById************" + id);
solrServer.deleteById(String.valueOf(id));
solrServer.commit();

}

你可能感兴趣的:(Spring集成Solr搜索引擎)