SpringDataSolr整合solr示例Demo

一、软件的安装

1.solr安装(默认端口号为9100)

//1.拷贝dist目录中的solr-4.10.3.war包到tomcat的webapps目录
//2.拷贝example/lib/ext的所有jar包到tomcat中的solr的\WEB-INF\lib目录下
//3.拷贝example/solr目录下的所有文件到本地硬盘改名为solrhome
//4.修改web.xml文件,将evn-entry注释放开,改路径为e:\solrhome

//测试
http://localhost:9100/solr/#/collection1/query

2.IK Analyzer(中文分词器)安装

//1.将jar包拷贝到\WEB-INF\lib目录下
//2.\WEB-INF创建classes目录,并拷贝mydict.dic、IKAnalyzer.cfg.xml、ext_stopword.dic
//3.在solrhome\collection1\conf修改schema.xml加入配置
<fieldType name="text_ik" class="solr.TextField">
     <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
</fieldType>
//4.测试http://localhost:9090/solr/#/collection1/analysis将FieldType改成text_ik查看效果

3.域配置

1)查询
q:*.*  前面是字段  后面是条件
start:从第几条开始查,rows:查多少条
2)修改schema.xml配置文件
  1. 在本地solrhome目录的collection1的conf下的schema.xml中增加以下内容
  • 普通域
//name:字段名称  type:字段类型 stored:是否存储分词前内容(复制域选择false) required:是否必填  indexed:索引(是否进行查询)  
	<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" />
  • 复制域:不占用存储空间,只是逻辑上等于其他几个域的总和
//multiValued 是否有多值  stored="false" 不需要存储
<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"/>
  • 动态域
//因为数据中的item_spec_后面的内容不固定所以用*号代替
<dynamicField name="item_spec_*" type="string" indexed="true" stored="true" />	
//配置好各种域信息,需要重新启动tomcat

二、SpringDataSolr的Demo

步骤:

1.创建springDataSolrDemo的maven的jar工程

2.pom坐标引入依赖,资料中的pom引入即可

3.spring配置文件放到resources目录下

4.拷贝资源文件中的TbItem.java类,该pojo类已经注解关联了solr字段和属性的关系

5.完成对solr库数据增加,新增测试类TestTemplate

1.依赖

 <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>

2.配置文件

  • 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: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">
   
   <!-- solr服务器地址 -->
   <solr:solr-server id="solrServer" url="http://127.0.0.1:9100/solr" />

  
   <!-- solr模板,使用solr模板可对索引库进行CRUD的操作 -->
   <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
   	<constructor-arg ref="solrServer" />
   </bean>

</beans>

3.拷贝pojo对象

  • @Field(“域”)注解
package cn.wys.test;

import org.apache.solr.client.solrj.beans.Field;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

public class TbItem  implements Serializable {
 
    @Field
    private Long id;
    
    @Field("item_title")
    private String title;
 
    @Field("item_price")
    private BigDecimal price;
  
    @Field("item_image")
    private String image;
   
    @Field("item_category")
    private String category;
    
    @Field("item_brand")
    private String brand;
    
    @Field("item_seller")
    private String seller;
   
   //get set....
}

4.solr的CURD

package cn.wys.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.data.solr.core.query.result.ScoredPage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.math.BigDecimal;
import java.util.ArrayList;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-solr.xml")
public class SolrTest {
    //注入solr
    @Autowired
    private SolrTemplate solrTemplate;

    @Test
    public void addToIndex(){
        TbItem item=new TbItem();
        item.setId(1l);//必须有id
        item.setTitle("P30");
        item.setBrand("华为");
        item.setCategory("手机");
        item.setPrice(new BigDecimal(4999));
        item.setImage("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1402367109,4157195964&fm=27&gp=0.jpg");
        item.setSeller("中国华为");

        TbItem item2=new TbItem();
        item2.setId(2l);//必须有id
        item2.setTitle("红米汤");
        item2.setBrand("小米");
        item2.setCategory("电器");
        item2.setPrice(new BigDecimal(2999));
        item2.setImage("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=846526770,4252093896&fm=27&gp=0.jpg");
        item2.setSeller("中国小米");

        TbItem item3=new TbItem();
        item3.setId(3l);//必须有id
        item3.setTitle("大锤子");
        item3.setBrand("锤子");
        item3.setCategory("家具");
        item3.setPrice(new BigDecimal(1999));
        item3.setImage("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3850549989,131691159&fm=27&gp=0.jpg");
        item3.setSeller("中国锤子");

        ArrayList<TbItem> itemList=new ArrayList<TbItem>();
        itemList.add(item);
        itemList.add(item2);
        itemList.add(item3);
        solrTemplate.saveBeans(itemList);
        solrTemplate.commit();
    }
    //根据id查询
    @Test
    public void findOne(){
        TbItem byId = solrTemplate.getById("1", TbItem.class);
        System.out.println(byId);
    }

    @Test
    public void testQuery(){
        SimpleQuery query = new SimpleQuery("*:*");//设置参数
        Criteria criteria=new Criteria("item_title");//设置库
        criteria = criteria.contains("红");
        query.addCriteria(criteria);
        //query.setRows(1);//起始页
        //query.setOffset(1); //查询起始页 (pageNo-1)* pageSize
        ScoredPage<TbItem> tbItems = solrTemplate.queryForPage(query, TbItem.class);
        for (TbItem tbItem : tbItems) {
            System.out.println(tbItem);
        }
    }

    //删除
    @Test
    public void dele(){
        //删除所有
//        Query query = new SimpleQuery("*:*");
//        solrTemplate.delete(query);
        solrTemplate.deleteById("1");
        solrTemplate.commit();//提交操作
    }
}

三、solr批量导入数据

步骤:

//创建pinyougou-solr-util的jar模块
//pom文件引入dao模块,拷贝资源提供的spring配置文件到spring目录(注意需要spring目录下)
//创建solrUtil工具类,目的是查询出所有tbitem状态为“1”的导入到solr库中

//注意坑classpath*:spring/applicationContext*.xml,两个星号
还有导入的时候因为修改了pojo,别忘记重新install一下

1.pojo添加动态域内容

  • 其他成员变量也要加Fileld注解
   @Dynamic
    @Field("item_spec_*")
    private Map<String,String> specMap;
    public Map<String, String> getSpecMap() {
		return specMap;
	}
	public void setSpecMap(Map<String, String> specMap) {
		this.specMap = specMap;
	}

2.配置文件 同上(二、2)

3.批量生成的工具类

package com.wys.solrutil;

import com.alibaba.fastjson.JSON;
import com.pinyougou.mapper.TbItemMapper;
import com.pinyougou.pojo.TbItem;
import com.pinyougou.pojo.TbItemExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 保存全部spu的solr数据
 */
@Component
public class SolrUtil {
    //注入spu
    @Autowired
    private TbItemMapper itemMapper;
    //注入solr操作对象
    @Autowired
    private SolrTemplate solrTemplate;

    /**
     * 保存全部spu数据(上线)
     */
    public void importDatToSolr(){
        //查询数据库中tbItem状态为1的所有数据
        TbItemExample itemExample=new TbItemExample();
        itemExample.createCriteria().andStatusEqualTo("1");
        List<TbItem> items=itemMapper.selectByExample(null);//itemExample
        //遍历 赋值动态域内容
        for (TbItem item : items) {
            Map specMap = JSON.parseObject(item.getSpec(), Map.class);
            item.setSpecMap(specMap);
        }
        //保存
        solrTemplate.saveBeans(items);
        solrTemplate.commit();
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath*:spring/applicationContext-*.xml");
        SolrUtil solrUtil = applicationContext.getBean("solrUtil", SolrUtil.class);
        solrUtil.importDatToSolr();        //执行方法
    }
}
  • solr的简单操作,如需要复杂操作后续更新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wuyuanshun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值