搜索引擎solr(六)--使用spring data 操作solr

一、简介

前面有介绍通过solr的java客户端操作solr,这里介绍另一种操作solr的方式,使用spring data操作

solr,进行数据的增删改查操作。

这里使用的solr版本是7.2.0,由于最新版本的spring-data(3.0.7.RELEASE)仅支持solr的java客户端版本6.6.1,因

此这使用solr的java客户端版本为6.6.1,spring的版本为5.0.4.RELEASE。

二、开发步骤

1、添加maven依赖


    org.apache.solr
    solr-solrj
    6.6.1


    org.springframework.data
    spring-data-solr
    3.0.7.RELEASE

2、定义bean类

import org.springframework.data.annotation.Id;
import org.springframework.data.solr.core.mapping.Indexed;
import org.springframework.data.solr.core.mapping.SolrDocument;

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

@SolrDocument(solrCoreName = "stu")
public class Stu implements Serializable {
    private static final long serialVersionUID = 566392553987979222L;

    @Id
    @Indexed(name = "stu_id")
    private String stuId;

    @Indexed(name = "stu_name")
    private String stuName;

    @Indexed(name = "create_time")
    private Date createTime;

    public Stu() {
    }

    public Stu(String stuId, String stuName) {
        this.stuId = stuId;
        this.stuName = stuName;
    }

    public Stu(String stuId, String stuName, Date createTime) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.createTime = createTime;
    }

    public String getStuId() {
        return stuId;
    }

    public void setStuId(String stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "Stu{" +
                "stuId='" + stuId + '\'' +
                ", stuName='" + stuName + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}

备注:通过注解@SolrDocument声明当前bean的core,通过注解@Id确认唯一id,

通过注解@Indexed可重定义字段属性(如通过name重定义字段名称)

3、定义repository类

import com.dragon.study.solr.bean.Stu;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.data.solr.repository.Highlight;
import org.springframework.data.solr.repository.SolrCrudRepository;

public interface StuSolrRepository extends SolrCrudRepository, String> {

    /**
     * 根据指定属性查询,高亮显示
     * @param stuName
     * @param pageable
     * @return
     */
    @Highlight(prefix = "", postfix = "")
    HighlightPage findByStuName(String stuName, Pageable pageable);

    /**
     * 分页模糊查询
     * @param stuName
     * @param pageable
     * @return
     */
    Page findByStuNameLike(String stuName, Pageable pageable);


    /**
     * 删除数据(模糊匹配)
     * @param stuName
     */
    void deleteByStuNameLike(String stuName);
}

4、定义spring配置文件spring-solr.xml

xml version="1.0" encoding="UTF-8"?>
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/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/data/solr
    http://www.springframework.org/schema/data/solr/spring-solr.xsd

">

    <solr:solr-client id="solrClient" url="http://192.168.0.107:8983/solr" />
    <solr:repositories base-package="com.dragon.study.solr" />
    id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
        ref="solrClient" />
    

5、测试

import com.dragon.study.solr.bean.Stu;
import com.dragon.study.solr.repository.StuSolrRepository;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.result.HighlightPage;

import java.util.Date;
import java.util.function.Consumer;

public class SolrSpringMain {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring-solr.xml");
        StuSolrRepository stuSolrRepository = ac.getBean(StuSolrRepository.class);

        //查询单个
        Stu stu = stuSolrRepository.findById("002").get();
        System.out.println(stu);

        //工具,输出结果
        Consumer consumer = s -> System.out.println(s);

        //查询所有
        Iterable it = stuSolrRepository.findAll();
        it.forEach(consumer);


        //分页查询所有数据
        Pageable pageable = PageRequest.of(0, 3);
        Page page = stuSolrRepository.findAll(pageable);
        System.out.println(page.getContent());

        //高亮查询
        HighlightPage highlightPage = stuSolrRepository.findByStuName("刘邦", pageable);
        System.out.println(highlightPage);

        //模糊查询
        Page likPage = stuSolrRepository.findByStuNameLike("刘", pageable);
        System.out.println(likPage);


        //保存或更新(当唯一id,即stu_id一样时)数据
//        Stu stu1 = new Stu("008", "小方", new Date());
        Stu stu1 = new Stu("009", "小明", new Date());
        stuSolrRepository.save(stu1);


        //根据唯一id删除数据
        stuSolrRepository.deleteById("008");

        //模糊匹配删除数据
        stuSolrRepository.deleteByStuNameLike("小");

        ac.close();
    }
}


三、附录

1、下面是从spring data solr官网上摘的reposity各种数据操作对应表格

Table 2. Supported keywords inside method names
Keyword Sample Solr Query String

And

findByNameAndPopularity

q=name:?0 AND popularity:?1

Or

findByNameOrPopularity

q=name:?0 OR popularity:?1

Is

findByName

q=name:?0

Not

findByNameNot

q=-name:?0

IsNull

findByNameIsNull

q=-name:[* TO *]

IsNotNull

findByNameIsNotNull

q=name:[* TO *]

Between

findByPopularityBetween

q=popularity:[?0 TO ?1]

LessThan

findByPopularityLessThan

q=popularity:[* TO ?0}

LessThanEqual

findByPopularityLessThanEqual

q=popularity:[* TO ?0]

GreaterThan

findByPopularityGreaterThan

q=popularity:{?0 TO *]

GreaterThanEqual

findByPopularityGreaterThanEqual

q=popularity:[?0 TO *]

Before

findByLastModifiedBefore

q=last_modified:[* TO ?0}

After

findByLastModifiedAfter

q=last_modified:{?0 TO *]

Like

findByNameLike

q=name:?0*

NotLike

findByNameNotLike

q=-name:?0*

StartingWith

findByNameStartingWith

q=name:?0*

EndingWith

findByNameEndingWith

q=name:*?0

Containing

findByNameContaining

q=name:*?0*

Matches

findByNameMatches

q=name:?0

In

findByNameIn(Collection names)

q=name:(?0…​ )

NotIn

findByNameNotIn(Collection names)

q=-name:(?0…​ )

Within

findByStoreWithin(Point, Distance)

q={!geofilt pt=?0.latitude,?0.longitude sfield=store d=?1}

Near

findByStoreNear(Point, Distance)

q={!bbox pt=?0.latitude,?0.longitude sfield=store d=?1}

Near

findByStoreNear(Box)

q=store[?0.start.latitude,?0.start.longitude TO ?0.end.latitude,?0.end.longitude]

True

findByAvailableTrue

q=inStock:true

False

findByAvailableFalse

q=inStock:false

OrderBy

findByAvailableTrueOrderByNameDesc

q=inStock:true&sort=name desc

2、若运行java代码时,出现报错Document is missing mandatory uniqueKey field: id时,这时说

明managed-schema中的id与bean中使用@id注解的字段名称不一致。

这时应修改managed-schema文件的唯一标识为stu_id,同时删除

你可能感兴趣的:(搜索引擎solr(六)--使用spring data 操作solr)