spring-data-solr

Posted 指北的司南

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring-data-solr相关的知识,希望对你有一定的参考价值。

  Spring Data Solr就是为了方便Solr的开发所研制的一个框架,其底层是对SolrJ(官方API)的封装

(1) 配置业务域

  vim /usr/local/solr/solrhome/collection1/conf/schema.xml

<field name="item_goodsid" type="long" indexed="true" stored="true"/>
<field name="item_title" type="text_ik" indexed="true" stored="true"/>
<field name="item_price" type="double" indexed="true" stored="true"/>
<field name="item_image" type="string" indexed="false" stored="true" />
<field name="item_category" type="string" indexed="true" stored="true" />
<field name="item_seller" type="text_ik" indexed="true" stored="true" />
<field name="item_brand" type="string" indexed="true" stored="true" />
<field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
<!-- 复制域 -->
<copyField source="item_title" dest="item_keywords"/> <copyField source="item_category" dest="item_keywords"/> <copyField source="item_seller" dest="item_keywords"/> <copyField source="item_brand" dest="item_keywords"/> <!-- 动态域 --> <dynamicField name="item_spec_*" type="string" indexed="true" stored="true" />

(2) 引入相关依赖

 

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-solr</artifactId>
    <version>1.5.5.RELEASE</version>
</dependency>

(3) 在相应pojo类中添加@Field注解

public class TbItem implements Serializable{
    private static final long serialVersionUID = 1L;

    @Field
    private Long id;

    @Field("item_title")
    private String title;

    private String sellPoint;

    @Field("item_price")
    private BigDecimal price;

    private Integer stockCount;

    private Integer num;

    private String barcode;

    @Field("item_image")
    private String image;

    private Long categoryid;

    private String status;

    private Date createTime;

    @Field("item_updatetime")
    private Date updateTime;

    private String itemSn;

    private BigDecimal costPirce;

    private BigDecimal marketPrice;

    private String isDefault;

    @Field("item_goodsid")
    private Long goodsId;

    private String sellerId;

    private String cartThumbnail;

    @Field("item_category")
    private String category;

    @Field("item_brand")
    private String brand;

    private String spec;

    @Field("item_seller")
    private String seller;
   
    @Dynamic
    @Field("item_spec_*")
    private Map<String,String> specMap;

(4) 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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
   <context:component-scan base-package="com.xxx.solrUtil"></context:component-scan> <!-- solr服务器地址 --> <solr:solr-server id="solrServer" url="http://127.0.0.1:8081/solr" /> <!-- solr模板,使用solr模板可对索引库进行CRUD的操作 --> <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate"> <constructor-arg ref="solrServer" /> </bean> </beans>

(5) 导入数据代码

@Component
public class SolrUtil {
    
    @Autowired
    private TbItemMapper itemMapper;
    
    @Autowired
    private SolrTemplate solrTemplate;
    
    public void importItemData(){
        TbItemExample example = new TbItemExample();
        Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo("1");
        
        List<TbItem> list = itemMapper.selectByExample(example);
        
        System.out.println("---商品列表---");
        
        for (TbItem tbItem : list) {
            System.out.println(tbItem.getId()+" "+ tbItem.getTitle()+ " "+tbItem.getPrice());
            // 动态域数据
            String spec = tbItem.getSpec();
            // FastJSON的泛型
            Map<String, String> map = JSON.parseObject(spec, new TypeReference<Map<String, String>>(){});
            tbItem.setSpecMap(map);
        }
        
        solrTemplate.saveBeans(list);
        solrTemplate.commit();
        
        System.out.println("---结束---");
        
    }
}

(6) 高亮显示

    // TODO 搜索关键字列表(关键字高亮)
    private Map<String, Object> searchList(Map<String, Object> searchMap) {
    // ************************ 关键字 ************************
     // 设置关键字搜索域(可以设置多个搜索域)
     Criteria criteria = new Criteria("item_keywords");
     criteria.is(searchMap.get("keywords"));
     query.addCriteria(criteria);
    // ************************ 条件过滤 ************************
    FilterQuery filterQuery = new SimpleFilterQuery();
    Criteria filterCriteria = new Criteria("item_title");
     filterCriteria.is(searchMap.get(key));
     filterQuery.addCriteria(filterCriteria);
     query.addFilterQuery(filterQuery);
    
// ************************ 高亮初始化 ************************ // 创建搜索对象(普通搜索) // Query query = new SimpleQuery("*:*"); // 创建搜索对象(高亮搜索) SimpleHighlightQuery query = new SimpleHighlightQuery(); // 设置高亮选项对象 HighlightOptions highlightOptions = new HighlightOptions(); highlightOptions.addField("item_title");// 设置高亮域 highlightOptions.setSimplePrefix("<span style=‘color: red;‘>");// 设置高亮前缀 highlightOptions.setSimplePostfix("</span>");// 设置高亮后缀 // 设置高亮选项 query.setHighlightOptions(highlightOptions);// 普通搜索 // ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); // ************************ 获取高亮 ************************ // 所搜结果 HighlightPage<TbItem> page = solrTemplate.queryForHighlightPage(query, TbItem.class); List<HighlightEntry<TbItem>> highlightedResult = page.getHighlighted();// 高亮结果集 for (HighlightEntry<TbItem> entry : highlightedResult) { List<Highlight> highlightList = entry.getHighlights(); // 只设定一个搜索域,entry.getHighlights()只有1个值,highlightList.get(0).getSnipplets()也只有1个值 if (highlightList.size() > 0 && highlightList.get(0).getSnipplets().size() > 0) { // 设置高亮 TbItem tbItem = entry.getEntity(); tbItem.setTitle(highlightList.get(0).getSnipplets().get(0)); // System.out.println(tbItem.getId() + " " + tbItem.getTitle() + " " + tbItem.getPrice()); } } map.put("rows", page.getContent());// 搜索结果 map.put("totalPages", page.getTotalPages());// 总页数 map.put("total", page.getTotalElements());// 总记录数 System.out.println("rows: " + page.getContent() + ",totalPages: " + page.getTotalPages() + ",total: " + page.getTotalElements()); return map; }

 (7) solrTemplate常用方法

  1) 添加/修改

solrTemplate.saveBean(item);

  2) 主键查询

Item item = solrTemplate.getById(1, Item.class);

  3) 主键删除

solrTemplate.deleteById("1");

  4) 分页

Query query=new SimpleQuery("*:*");
query.setOffset(20);//开始索引(默认0)
query.setRows(20);//每页记录数(默认10)
ScoredPage<Item> page = solrTemplate.queryForPage(query, Item.class);
List<Item> list = page.getContent();

  5) 条件查询

Query query=new SimpleQuery("*:*");
Criteria criteria=new Criteria("item_title").contains("2");
criteria=criteria.and("item_title").contains("5");        
query.addCriteria(criteria);
ScoredPage<Item> page = solrTemplate.queryForPage(query, Item.class);
List<TbItem> list = page.getContent();

  6) 删除所有

Query query=new SimpleQuery("*:*");
solrTemplate.delete(query);

  7) 提交(cud)

solrTemplate.commit();

   8) 关于动态域搜索

item_spec_网络;item_spec_机身内存
spec = {‘key1‘:‘value1‘, ‘key2‘:‘value2‘};spec = {‘网络‘:‘value1‘, ‘机身内存‘:‘value2‘} Map<String, String> spec = (Map<String, String>) searchMap.get("spec"); for (String key : spec.keySet()) { String value = spec.get(key); FilterQuery filterQuery = new SimpleFilterQuery(); Criteria filterCriteria = new Criteria("item_spec_" + key); filterCriteria.is(value); filterQuery.addCriteria(filterCriteria); query.addFilterQuery(filterQuery); }

 
















以上是关于spring-data-solr的主要内容,如果未能解决你的问题,请参考以下文章

使用 Spring-Data-Solr 注入存储库

使用spring-data-solr做solr客户端

Spring-Data-Solr 如何提供认证数据

Solr7.x学习-使用spring-data-solr

spring-data-solr

使用 SolrTemplate 使用 Spring-data-solr 进行枢轴分面