spring data solr的使用

solr的安装

1,需要把solr的安装包下载下来,将其解压。
2,把solr服务对应的war包复制到tomcat的webapps目录下:

solr-4.10.3\dist\solr-4.10.3.war

3,启动tomcat,目的就是让tomcat对war包进行解压. 关闭tomcat
4、把solr在运行的时候所需要的扩展的jar包复制到solr应用的WEB-INF下的lib目录下

扩展jar包: solr-4.10.3\example\lib\ext\*.jar

5、创建一个solrHome,solrHome就是solr的家,在solrHome中存在solrCore,solrCore就是solr的实例,每一个solrCore都可以对外提供独立的索引和搜索服务。

一个solrHome下可以存在多个solrCore,在例子程序中:

solrHome指的就是:

solr-4.10.3\example\solr

solrCore值得就是:

solr-4.10.3\example\solr\collection1

6、在solr的应用中去配置solrHome所在位置: 在solr应用的web.xml文件中进行配置

<env-entry>
    <env-entry-name>solr/homeenv-entry-name>
    <env-entry-value>D:\solr\solrHomeenv-entry-value>
    <env-entry-type>java.lang.Stringenv-entry-type>
env-entry>

7、启动tomcat

配置好后运行tomcat ;再访问http://IP:8080/solr/进入到solr界面
spring data solr的使用_第1张图片

在solr工程中添加IK分词器
1、把IKAnalyzer2012FF_u1.jar 添加到 solr 工程的 lib 目录下
2、创建WEB-INF/classes文件夹 把扩展词典、停用词词典、配置文件放到 solr 工程的 WEB-INF/classes 目录下。
3、修改 Solrhome 的 schema.xml 文件,配置一个 FieldType,使用 IKAnalyzer

<fieldType name="text_ik" class="solr.TextField">
     <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
fieldType>

solr域

1,概念
域相当于数据库的表字段,用户存放数据,因此用户根据业务需要去定义相关的Field(域),一般来说,每一种对应着一种数据,用户对同一种数据进行相同的操作。
域的常用属性:
name: 指定域的名称
type: 指定域的类型
indexed: 是否索引
stored: 是否储存
required: 是否必须
multiValued: 是否多值
根据数据库的每个字段,以及业务需求指定属性

2,域的solrhome的schema.xml文件
这个配置文件是配置业务字段的。
Solr中的字段必须是先定义后使用。该配置要与我们的实际业务关联。
业务字段判断标准:
在搜索时是否需要在此字段上进行搜索。例如:商品名称、商品的卖点、商品的描述
后续的业务是否需要用到此字段。例如:商品id。
本人这次项目需要用到的字段:
1)、商品id
2)、商品title
3)、卖点sell_point
4)、价格price
5)、商品图片image
6)、商品分类名称category_name
7)、商品描述item_des

为了测试,配置一个商品的字段(与上面字段判断标准的例子无关)

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

3,复制域
复制域常用于多域搜索,如:电商项目中搜索商品,既要在名字域中搜索也要在描述域中搜索,传统的做法需要手工写两次,而solr想发送一次请求,可到两个域中搜索,为此,引入了复制域的概念,将两个域的域名复制到一个text文本域中。
-------域的类型:
String—>solr.StrField
boolean—>solr.BoolField
int—>solr.TrieIntField
float—>solr.TrieFloatField
long—>solr.TrieLongField
double—>solr.TrieDoubleField
text_general—>solr.TextField
测试,添加配置到solrhome的schema.xml文件

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

4,动态域
当我们需要动态扩充字段时,我们需要使用动态域。对于品优购,规格的值是不确定的,所以我们需要使用动态域来实现。需要实现的效果如下:

spring data solr的使用_第2张图片

添加配置到solrhome的schema.xml文件

<dynamicField name="item_spec_*" type="string" indexed="true" stored="true" />	

spring data solr的准备

(1)创建maven工程,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


<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-server id="solrServer" url="http://127.0.0.1:8080/solr" />
	
	<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
		<constructor-arg ref="solrServer" />
	bean>
beans>

springdataSolr入门-注解

创建 cn.solrtest.pojo 包,写TbItem实体类到本工程 ,属性使用@Field注解标识 。 如果属性与配置文件定义的域名称不一致,需要在注解中指定域名称

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_goodsid")
     private Long goodsId;

    @Field("item_category")
    private String category;

    @Field("item_brand")
    private String brand;

    @Field("item_seller")
	private String seller;
.......
}

spring data solr的使用_第3张图片

springdataSolr入门-增加修改

增加
实体类pojo的属性 与 solrhome配置文件中域字段配置name属性值一致,不一致的pojo属性上加

@Field(“配置文件中name属性值”)

测试类

package cn.solr.test;

import cn.solr.pojo.TbItem;
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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.math.BigDecimal;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-solr.xml")
public class TestTemplate {

    @Autowired
    private SolrTemplate solrTemplate;

    @Test
    public void testAdd(){
        TbItem item = new TbItem();
        item.setId(1L);
        item.setBrand("荣耀");
        item.setCategory("手机");
        item.setGoodsId(1L);
        item.setSeller("荣耀手机店");
        item.setTitle("荣耀magic2");
        item.setPrice(new BigDecimal(3700));
        //item已经封装好,存入solr
        solrTemplate.saveBean(item);
        //提交
        solrTemplate.commit();
    }

}

启动solr所在的tomcat 运行测试类后 访问127.0.0.1:8080/solr

spring data solr的使用_第4张图片

修改和添加一样 只要id不变,solr会更新,

springdataSolr入门-根据主键查询删除

**查询:**solrTemplate.getById(id,所要封装的类型)

 //根据id在solr中查询
    @Test
    public void testFindOne(){
        //id查询 并封装成TbItem.class
       TbItem item = solrTemplate.getById(1,TbItem.class);
        System.out.println(item);
    }

打印结果

spring data solr的使用_第5张图片
**删除:**solrTemplate.deleteById(主键id)

 //根据主键删除
    @Test
    public void testDelete(){
        solrTemplate.deleteById("1");
        solrTemplate.commit();
    }

springdataSolr入门-批量插入数据

循环 赋值不同的id 实现批量的插入数据
放入一个List集合中 同一提交

 @Test
    public void testAddList(){
        List<TbItem> list=new ArrayList();

        for(int i=0;i<100;i++){
            TbItem item=new TbItem();
            item.setId(i+1L);
            item.setBrand("华为");
            item.setCategory("手机");
            item.setGoodsId(1L);
            item.setSeller("华为专卖店");
            item.setTitle("华为Mate"+i);
            item.setPrice(new BigDecimal(2000+i));
            list.add(item);
        }

        solrTemplate.saveBeans(list);
        solrTemplate.commit();
    }

springdataSolr入门-分页查询

 //分页查询
    @Test
    public void testpageQuery(){
        Query query = new SimpleQuery("*:*");
        query.setOffset(20);//开始索引(默认为0)
        query.setRows(20);//每页记录条数(默认为10)
        ScoredPage<TbItem> page  =  solrTemplate.queryForPage(query,TbItem.class);

        //输出总记录数
        System.out.println("总记录数:" + page.getTotalElements() );

        List<TbItem> list = page.getContent();
        showList(list);
    }

    private void showList(List<TbItem> list){
        for (TbItem item : list){
            System.out.println(item.getTitle() + item.getPrice());
        }
    }

springdataSolr入门-条件查询

 //条件查询
    @Test
    public  void testPageQueryMutil(){
        //查询范围 query
        Query query = new SimpleQuery("*:*");
        Criteria criteria = new Criteria("item_title").contains("2");
        criteria = criteria.and("item_title").contains("5");
        query.addCriteria(criteria);
        //query.setOffset(20);//开始索引(默认0)
        //query.setRows(20);//每页记录数(默认10)
        ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class);
        System.out.println("总记录数:"+page.getTotalElements());
        List<TbItem> list = page.getContent();
        //为分页抽取的方法方便打印
        showList(list);
    }

spring data solr的使用_第6张图片

springdataSolr全部删除

 @Test
    public void testDeleteAll(){
        Query query=new SimpleQuery("*:*");
        solrTemplate.delete(query);
        solrTemplate.commit();
    }

你可能感兴趣的:(Java基础)