Skip to content
标签
搜索
spring
字数
1107 字
阅读时间
6 分钟

一、概述

Spring Data ElasticSearch是SpringData技术对ElasticSearch原生API封装之后的产物,它通过对原生API的封装,使得程序员可以简单的对ElasticSearch进行各种操作。

1.1 实现CRUD

参考 [入门Demo](###2.1 入门Demo)

1.2 命名规则查询

关键字命名规则解释示例
andfindByField1AndField2根据Field1和Field2获得数据findByTitleAndContent
orfindByField1OrField2根据Field1或Field2获得数据findByTitleOrContent
isfindByField根据Field获得数据findByTitle
notfindByFieldNot根据Field获得补集数据findByTitleNot
betweenfindByFieldBetween获得指定范围的数据findByPriceBetween
lessThanEqualfindByFieldLessThan获得小于等于指定值的数据findBy

在dao接口中按照规则进行自定义查询方法

二、使用示例

2.1 入门Demo

依赖

xml
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId> 
    <version>5.6.8</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.6.8</version>
</dependency>
<dependency> 
    <groupId>org.springframework.data</groupId> 
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>

配置

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:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch
        http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 扫描dao包 -->
    <elasticsearch:repositories base-package="com.itheima"/>

    <!-- 配置Client -->
    <elasticsearch:transport-client id="client" cluster-nodes="192.168.106.128:9300"/>

    <!-- 配置搜索模板 -->
    <bean id="elasticsearchTemplate"
          class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="client"/>
    </bean>
</beans>

实体类

java
package com.itheima.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

//indexName指定索引名称   type  指定类型名称
@Document(indexName = "heima-sd", type = "article")
public class Article {

    @Id
    @Field(index = false, type = FieldType.Integer)
    private Integer id;

    /**
     * index:是否设置分词  默认是true
     * analyzer:存储时使用的分词器
     * searchAnalyze:搜索时使用的分词器
     * store:是否存储 默认是false
     * type: 数据类型 默认值是FieldType.Auto
     */
    @Field(analyzer = "ik_smart", searchAnalyzer = "ik_smart", store = true, type = FieldType.text)
    private String title;

    @Field(analyzer = "ik_smart", searchAnalyzer = "ik_smart", store = true, type = FieldType.text)
    private String context;

    @Field(store = true, type = FieldType.Integer)
    private Integer hits;

    // 省略get/set方法及toString
}

dao层接口

java
package com.itheima.dao;

import com.itheima.domain.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

//自定义的接口需要继承ElasticsearchRepository<实体类型,主键类型>  基本的crud 分页
public interface ArticleDao extends ElasticsearchRepository<Article, Integer> {

    //根据标题查询
    List<Article> findByTitle(String title);

    //根据标题或内容查询
    List<Article> findByTitleOrContext(String title, String context);

    //根据标题或内容查询(含分页)
    List<Article> findByTitleOrContext(String title, String context, Pageable pageable);


}

调用测试

java
package com.itheima.test;

import com.itheima.dao.ArticleDao;
import com.itheima.domain.Article;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Optional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-es.xml")
public class EsTest {

    @Autowired
    private ElasticsearchTemplate template;

    @Autowired
    private ArticleDao articleDao;

    //通过SpringData ES技术向ElasticSearch数据库存储一条数据
    @Test
    public void testSave() {
        //创建索引
        template.createIndex(Article.class);

        //创建映射
        template.putMapping(Article.class);

        //创建文档
        Article article = new Article();
        article.setId(1);
        article.setTitle("sd-黑马程序员");
        article.setContext("sd-黑马程序员很棒");

        //保存文档
        articleDao.save(article);
    }

    //修改
    @Test
    public void testUpdate() {

        //判断数据库中是否有你指定的id的文档,如果没有,就进行保存,如果有,就进行更新
        Article article = new Article();
        article.setId(1);
        article.setTitle("sd-黑马程序员1");
        article.setContext("sd-黑马程序员很棒1");

        articleDao.save(article);
    }

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

    //重新构建数据
    @Test
    public void makeData() {
        //创建索引
        template.createIndex(Article.class);

        //创建映射
        template.putMapping(Article.class);

        for (int i = 1; i <= 10; i++) {
            //创建文档
            Article article = new Article();
            article.setId(i);
            article.setTitle("sd-黑马程序员" + i);
            article.setContext("sd-黑马程序员很棒" + i);
            article.setHits(100 + i);
            //保存文档
            articleDao.save(article);
        }
    }

    //查询所有
    @Test
    public void testFindAll() {
        Iterable<Article> all = articleDao.findAll();
        for (Article article : all) {
            System.out.println(article);
        }
    }

    //主键查询
    @Test
    public void testFindById() {
        Optional<Article> opt = articleDao.findById(1);
        System.out.println(opt.get());
    }

    //分页查询
    @Test
    public void testFindAllWithPage() {
        //设置分页条件
        Pageable pageable = PageRequest.of(1, 3);//page代表的页码,从0开始

        Page<Article> page = articleDao.findAll(pageable);

        for (Article article : page.getContent()) {
            System.out.println(article);
        }
    }

    //排序查询
    @Test
    public void testFindAllWithSort() {
        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));

        Iterable<Article> all = articleDao.findAll(sort);
        for (Article article : all) {
            System.out.println(article);
        }
    }

    //分页+排序查询
    @Test
    public void testFindAllWithPageAndSort() {
        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));

        //设置分页条件
        Pageable pageable = PageRequest.of(1, 3, sort);//page代表的页码,从0开始

        Page<Article> page = articleDao.findAll(pageable);

        for (Article article : page.getContent()) {
            System.out.println(article);
        }
    }

    //根据标题查询
    @Test
    public void testFindByTitle() {
        List<Article> articles = articleDao.findByTitle("员");
        for (Article article : articles) {
            System.out.println(article);
        }
    }


    //根据标题查询
    @Test
    public void testFindByTitleOrContext() {
        List<Article> articles = articleDao.findByTitleOrContext("程序员", "程序员");
        for (Article article : articles) {
            System.out.println(article);
        }
    }

    //根据标题查询
    @Test
    public void testFindByTitleOrContextWithPage() {

        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));

        //设置分页条件
        Pageable pageable = PageRequest.of(1, 3, sort);//page代表的页码,从0开始

        List<Article> articles = articleDao.findByTitleOrContext("程序员", "程序员", pageable);
        for (Article article : articles) {
            System.out.println(article);
        }
    }
}