Spring Data Solr操作solr的简单案例

Spring Data Solr简介

  虽然支持任何编程语言的能力具有很大的市场价值,你可能感兴趣的问题是:我如何将Solr的应用集成到Spring中?可以,Spring Data Solr就是为了方便Solr的开发所研制的一个框架,其底层是对SolrJ(官方API)的封装。

简单案例:

pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>1.5.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
</dependencies>

在src/main/resources下创建 applicationContext-solr.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:solr="http://www.springframework.org/schema/data/solr"
xsi:schemaLocation="http://www.springframework.org/schema/data/solr
http://www.springframework.org/schema/data/solr/spring-solr-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- solr服务器地址 -->
<solr:solr-server id="solrServer" url="http://192.168.44.35:8080/solr" /> <!-- solr模板,使用solr模板可对索引库进行CRUD的操作 -->
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg ref="solrServer" />
</bean>
</beans>

如果连的是solrCloud集群:

    <!-- solr服务器地址
<solr:solr-server id="solrServer" url="http://192.168.44.35:8080/solr" />
-->
<bean id="solrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer">
<constructor-arg value="192.168.25.140:2181,192.168.25.140:2182,192.168.25.140:2183" />
<property name="defaultCollection" value="collection1"></property>
</bean>

@Field 注解

public class TestBean implements Serializable {
// @Field 用来指定那些成员属性是document的字段的
@Field
private String id;
@Field("title")
private String title;
@Field("content")
private String content;
@Field("name")
private String name;
//getter and setters
}

使用spring data solr执行CURD

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-solr.xml")
public class TestTemplate { @Autowired
private SolrTemplate solrTemplate; //添加
@Test
public void testAdd(){
TestBean item=new TestBean();
item.setId("1");
item.setTitle("testTitle");
item.setContent("testContent");
item.setName("testName");
solrTemplate.saveBean(item);
solrTemplate.commit();
}
//根据id删除
@Test
public void testDelete(){
solrTemplate.deleteById("1");
solrTemplate.commit();
}
//分页查询
@Test
public void testPageQuery(){
Query query=new SimpleQuery("*:*");
query.setOffset(20);//开始索引(默认0)
query.setRows(20);//每页记录数(默认10)
ScoredPage<TestBean> page = solrTemplate.queryForPage(query, TestBean.class);
System.out.println("总记录数:"+page.getTotalElements());
List<TestBean> list = page.getContent();
showList(list);
}
//显示记录数据
private void showList(List<TestBean> list){
for(TestBean item:list){
System.out.println(item.getTitle());
}
}
//条件查询
@Test
public void testPageQueryMutil(){
Query query=new SimpleQuery("*:*");
Criteria criteria=new Criteria("title").contains("2");
criteria=criteria.and("title").contains("5");
query.addCriteria(criteria);
//query.setOffset(20);//开始索引(默认0)
//query.setRows(20);//每页记录数(默认10)
ScoredPage<TestBean> page = solrTemplate.queryForPage(query, TestBean.class);
System.out.println("总记录数:"+page.getTotalElements());
List<TestBean> list = page.getContent();
showList(list);
}
//删除全部
@Test
public void testDeleteAll(){
Query query=new SimpleQuery("*:*");
solrTemplate.delete(query);
solrTemplate.commit();
}
}

补充:模拟商品(sku) 查询  数据存放在solr中  查询相关条件放到redis做缓存

package com.zy.search.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.zy.pojo.TbItem;
import com.zy.search.service.ItemSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.*;
import org.springframework.data.solr.core.query.result.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; @Service
public class ItemSearchServiceImpl implements ItemSearchService {
@Autowired
private SolrTemplate solrTemplate; @Autowired
private RedisTemplate redisTemplate; /**
* 模拟商品查询方法
* searchMap格式 {'keywords': '', 'category': '', 'brand': '', 'spec': {},'price': '','pageNo': 1,'pageSize': 20,'sortField':'','sort':''}
*/
@Override
public Map<String, Object> search(Map searchMap) {
Map<String, Object> map = new HashMap<>();
//按关键字查询 高亮显示
map.putAll(searchResultList(searchMap));
//根据关键字查询商品分类
List categoryList = searchCategoryList(searchMap);
map.put("categoryList", categoryList);
//查询品牌和规格列表
String categoryName = (String) searchMap.get("category");
if (categoryList == null || !"".equals(categoryName)) {//如果有分类名称
map.putAll(searchBrandAndSpecList(categoryName));
} else {//如果没有分类名称,按照第一个查询
if (categoryList.size() > 0) {
map.putAll(searchBrandAndSpecList((String) categoryList.get(0)));
}
}
return map;
} /**
* 第二版 筛选过滤后的 带高亮的数据
*/
private Map<String, Object> searchResultList(Map searchMap) {
Map<String, Object> map = new HashMap<>(); //***********************关键字空格处理***********************
String keywords = (String) searchMap.get("keywords");
searchMap.put("keywords", keywords.replace(" ", "")); HighlightQuery query = new SimpleHighlightQuery(); //***********************按关键字查询***********************
Criteria criteria = new Criteria("item_keywords").is(searchMap.get("keywords"));
query.addCriteria(criteria); //---------------------------过滤查询start--------------------------- //***********************按分类筛选***********************
if (searchMap.get("category") != null && !"".equals(searchMap.get("category"))) {
Criteria filterCriteria = new Criteria("item_category").is(searchMap.get("category"));
FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
query.addFilterQuery(filterQuery);
}
//***********************按品牌筛选***********************
if (searchMap.get("brand") != null && !"".equals(searchMap.get("brand"))) {
Criteria filterCriteria = new Criteria("item_brand").is(searchMap.get("brand"));
FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
query.addFilterQuery(filterQuery);
}
//***********************规格过滤筛选***********************
if (searchMap.get("spec") != null) {
Map<String, String> specMap = (Map) searchMap.get("spec");
for (String key : specMap.keySet()) {
Criteria filterCriteria = new Criteria("item_spec_" + key).is(specMap.get(key));
FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
query.addFilterQuery(filterQuery);
}
} //***********************价格过滤筛选***********************
if (!"".equals(searchMap.get("price"))) {
String[] price = ((String) searchMap.get("price")).split("-");
if (!price[0].equals("0")) {//如果区间起点不等于0
Criteria filterCriteria = new Criteria("item_price").greaterThanEqual(price[0]);
FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
query.addFilterQuery(filterQuery);
}
if (!price[1].equals("*")) {//如果区间终点不等于*
Criteria filterCriteria = new Criteria("item_price").lessThanEqual(price[1]);
FilterQuery filterQuery = new SimpleFilterQuery(filterCriteria);
query.addFilterQuery(filterQuery);
}
}
//---------------------------过滤查询end--------------------------- //***********************分页查询**********************
Integer pageNo = (Integer) searchMap.get("pageNo");//提取页码
if (pageNo == null) {
pageNo = 1;//默认第一页
}
Integer pageSize = (Integer) searchMap.get("pageSize");//每页记录数
if (pageSize == null) {
pageSize = 20;//默认20
}
query.setOffset((pageNo - 1) * pageSize);//从第几条记录查询
query.setRows(pageSize); //***********************排序***********************
String sortValue = (String) searchMap.get("sort");//ASC DESC
String sortField = (String) searchMap.get("sortField");//排序字段
if (sortValue != null && !sortValue.equals("")) {
if (sortValue.equals("ASC")) {
Sort sort = new Sort(Sort.Direction.ASC, "item_" + sortField);
query.addSort(sort);
}
if (sortValue.equals("DESC")) {
Sort sort = new Sort(Sort.Direction.DESC, "item_" + sortField);
query.addSort(sort);
}
} //***********************高亮设置***********************
//设置高亮的域
HighlightOptions highlightOptions = new HighlightOptions().addField("item_title");
//高亮前缀
highlightOptions.setSimplePrefix("<em style='color:red'>");
//高亮后缀
highlightOptions.setSimplePostfix("</em>");
//设置高亮选项
query.setHighlightOptions(highlightOptions); //***********************获取数据***********************
HighlightPage<TbItem> page = solrTemplate.queryForHighlightPage(query, TbItem.class); //***********************设置高亮结果***********************
List<HighlightEntry<TbItem>> highlighted = page.getHighlighted();
for (HighlightEntry<TbItem> h : highlighted) {//循环高亮入口集合
TbItem item = h.getEntity();//获取原实体类
if (h.getHighlights().size() > 0 && h.getHighlights().get(0).getSnipplets().size() > 0) {
item.setTitle(h.getHighlights().get(0).getSnipplets().get(0));//设置高亮的结果
}
}
//***********************给map赋值***********************
map.put("rows", page.getContent());
map.put("total", page.getTotalElements());
map.put("totalPages", page.getTotalPages());
return map;
} /**
* 第一版 单纯读取数据
*/
private Map<String, Object> searchBase(Map searchMap) {
Map<String, Object> map = new HashMap<>();
Query query = new SimpleQuery();
Criteria criteria = new Criteria("item_keywords").is(searchMap.get("keywords"));
query.addCriteria(criteria);
ScoredPage<TbItem> scoredPage = solrTemplate.queryForPage(query, TbItem.class);
List<TbItem> itemList = scoredPage.getContent(); map.put("rows", itemList);
map.put("total", scoredPage.getTotalElements());
map.put("totalPages", scoredPage.getTotalPages());
return map;
} /**
* 查询品牌和规格列表
*/
private Map searchBrandAndSpecList(String category) {
Map map = new HashMap();
Long typeId = (Long) redisTemplate.boundHashOps("itemCat").get(category);//获取模板ID
if (typeId != null) {
//根据模板ID查询品牌列表
List brandList = (List) redisTemplate.boundHashOps("brandList").get(typeId);
map.put("brandList", brandList);//返回值添加品牌列表
//根据模板ID查询规格列表
List specList = (List) redisTemplate.boundHashOps("specList").get(typeId);
map.put("specList", specList);
}
return map;
} /**
* 查询分类列表 category 根据搜索关键字分组查询
*/
private List searchCategoryList(Map searchMap) {
List<String> list = new ArrayList();
Query query = new SimpleQuery();
//按照关键字查询
Criteria criteria = new Criteria("item_keywords").is(searchMap.get("keywords"));
query.addCriteria(criteria);
//设置分组选项
GroupOptions groupOptions = new GroupOptions().addGroupByField("item_category");
query.setGroupOptions(groupOptions);
//得到分组页
GroupPage<TbItem> page = solrTemplate.queryForGroupPage(query, TbItem.class);
//根据列得到分组结果集
GroupResult<TbItem> groupResult = page.getGroupResult("item_category");
//得到分组结果入口页
Page<GroupEntry<TbItem>> groupEntries = groupResult.getGroupEntries();
//得到分组入口集合
List<GroupEntry<TbItem>> content = groupEntries.getContent();
for (GroupEntry<TbItem> entry : content) {
list.add(entry.getGroupValue());//将分组结果的名称封装到返回值中
}
return list;
}
}
上一篇:MongoDB十二种最有效的模式设计【转】


下一篇:Spring Data Solr教程(翻译) 开源的搜索服务器