Spring Data Solr操作solr的简单案例

Spring Data Solr操作solr的简单案例

Spring Data Solr简介

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

简单案例:

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.datagroupId>
        <artifactId>spring-data-solrartifactId>
        <version>1.5.5.RELEASEversion>
    dependency> 
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.9version>
    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-server id="solrServer" url="http://192.168.44.35:8080/solr" />

   
    
    <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
        <constructor-arg ref="solrServer" />
    bean>
beans>

如果连的是solrCloud集群:

        
    <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 page = solrTemplate.queryForPage(query, TestBean.class);
        System.out.println("总记录数:"+page.getTotalElements());
        List list = page.getContent();
        showList(list);
    }    
    //显示记录数据
    private void showList(List 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 page = solrTemplate.queryForPage(query, TestBean.class);
        System.out.println("总记录数:"+page.getTotalElements());
        List 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 search(Map searchMap) {
        Map 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 searchResultList(Map searchMap) {
        Map 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 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("");
        //高亮后缀
        highlightOptions.setSimplePostfix("");
        //设置高亮选项
        query.setHighlightOptions(highlightOptions);

        //***********************获取数据***********************
        HighlightPage page = solrTemplate.queryForHighlightPage(query, TbItem.class);

        //***********************设置高亮结果***********************
        List> highlighted = page.getHighlighted();
        for (HighlightEntry 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 searchBase(Map searchMap) {
        Map map = new HashMap<>();
        Query query = new SimpleQuery();
        Criteria criteria = new Criteria("item_keywords").is(searchMap.get("keywords"));
        query.addCriteria(criteria);
        ScoredPage scoredPage = solrTemplate.queryForPage(query, TbItem.class);
        List 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 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 page = solrTemplate.queryForGroupPage(query, TbItem.class);
        //根据列得到分组结果集
        GroupResult groupResult = page.getGroupResult("item_category");
        //得到分组结果入口页
        Page> groupEntries = groupResult.getGroupEntries();
        //得到分组入口集合
        List> content = groupEntries.getContent();
        for (GroupEntry entry : content) {
            list.add(entry.getGroupValue());//将分组结果的名称封装到返回值中
        }
        return list;
    }
}

 

posted @ 2017-11-13 20:41 青衫仗剑 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(Spring Data Solr操作solr的简单案例)