Solr索引库可用作实现搜索功能,并发性能比MySQL更好。
Spring整合Solr
Spring配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<context:component-scan base-package="cn.xing"/>
<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
<constructor-arg index="0" value="http://192.168.159.130:8080/solr"/>
</bean>
</beans>
Java代码操作Solr索引库:
package cn.xing.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.xing.pojo.SearchItem;
import cn.xing.pojo.SearchResult;
/**
* 操作solr索引库
*
* @author Xing
*
*/
@Service
public class Operation {
@Autowired
private SolrServer solrServer;// 是配置的httpSolrServer
/**
* 把所有商品导入索引库,商品对象SearchItem必须和solr配置的业务域字段、类型相同
*/
public void imprtSolrItem() {
try {
List<SearchItem> list = new ArrayList<SearchItem>();
list.add(new SearchItem("1", "湖北", "黄鹤楼", 12, "image1", "省市"));
list.add(new SearchItem("2", "河南", "开封", 12, "image2", "省市"));
list.add(new SearchItem("3", "3", "3", 12, "image2", "222"));
// 把list放入索引库
for (SearchItem searchItem : list) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", searchItem.getId());
doc.addField("item_title", searchItem.getTitle());
doc.addField("item_sell_point", searchItem.getSell_point());
doc.addField("item_price", searchItem.getPrice());
doc.addField("item_image", searchItem.getImage());
doc.addField("item_category_name", searchItem.getCategory_name());
solrServer.add(doc);
}
solrServer.commit();
System.out.println("数据导入成功");
} catch (Exception e) {
e.printStackTrace();
}
}
// 根据查询条件SolrQuery,查询索引库
public List<SearchItem> querySolr(SolrQuery query) throws SolrServerException {
// 根据条件查询索引库
QueryResponse queryResponse = solrServer.query(query);
SolrDocumentList results = queryResponse.getResults();
// 取出总记录数
long num = results.getNumFound();
System.out.println("查询结果的数据条数:" + num);
// 取出商品列表,高亮关键词
// Map<商品id,Map<商品属性字段,List<字段的值>>>
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
List<SearchItem> itemList = new ArrayList<>();
for (SolrDocument solrDocument : results) {
SearchItem item = new SearchItem();
item.setId((String) solrDocument.get("id"));
item.setCategory_name((String) solrDocument.get("item_category_name"));
item.setImage((String) solrDocument.get("item_image"));
item.setPrice((long) solrDocument.get("item_price"));
item.setSell_point((String) solrDocument.get("item_sell_point"));
// 取高亮结果,商品标题
List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
if (list != null && list.size() > 0) {
item.setTitle(list.get(0));// 拿到该商品标题
} else {
item.setTitle((String) solrDocument.get("item_title"));
}
itemList.add(item);
}
return itemList;
}
/**
* 根据关键词在solr索引库中搜索商品并分页。
*/
public SearchResult search(String keyword, int page, int rows) throws Exception {
// 设置查询条件,调用querySolr()方法查询
SolrQuery query = new SolrQuery();
query.setQuery(keyword);// 设置查询条件
if (page <= 0)
page = 1;
query.setStart((page - 1) * rows);// 设置分页索引
query.setRows(rows);// 设置查询条数
// 设置默认搜索域
query.set("df", "item_title");
// 设置高亮显示
query.setHighlight(true);
query.addHighlightField("item_title");
query.setHighlightSimplePre("<em style=\"color:red\">");
query.setHighlightSimplePost("</em>");
// 执行查询
List<SearchItem> itemList = this.querySolr(query);
// 设置返回结果
SearchResult rs = new SearchResult();
rs.setItemList(itemList);
/*
* // 设置总页数 int totalpages = rs.getRecourdCount() / rows; if
* (rs.getRecourdCount() % rows > 0) totalpages++; rs.setTotalPages((long)
* totalpages);
*/
return rs;
}
}
分页查询数据封装:
package cn.xing.pojo;
import java.io.Serializable;
import java.util.List;
/**
* 搜素商品的结果。对页面需要的数据的封装。
*
* @author Xing
*
*/
public class SearchResult implements Serializable {
private Long totalPages;
private Integer recourdCount;
private List<SearchItem> itemList;
}
Solr数据对应的pojo:
package cn.xing.pojo;
import java.io.Serializable;
import org.apache.commons.lang3.StringUtils;
public class SearchItem implements Serializable {
@Override
public String toString() {
return "SearchItem [id=" + id + ", title=" + title + ", sell_point=" + sell_point + ", price=" + price
+ ", image=" + image + ", category_name=" + category_name + "]";
}
// 类型和solr的中文分析器里的schema.xml中配置的type必须一样
private String id;
private String title;
private String sell_point;
private long price;
private String image;
private String category_name;
// 搜索结果页面展示一张图片
public String[] getImages() {
String image2 = this.getImage();
if (StringUtils.isNotBlank(image2)) {
String[] imagesArr = image2.split(",");
return imagesArr;
}
return null;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Java测试代码:
package cn.xing.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.xing.pojo.SearchItem;
import cn.xing.pojo.SearchResult;
public class test {
public static void main(String[] args) throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Operation operation = ac.getBean(Operation.class);
// 导入数据
operation.imprtSolrItem();
// SearchResult search = operation.search("明明就", 1, 1);
SearchResult search = operation.search("3", 1, 10);
List<SearchItem> itemList = search.getItemList();
for (SearchItem searchItem : itemList) {
System.out.println(searchItem);
}
}
}