SpringDataElasticSearch快速入门

  • Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 。Spring Data为Elasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域为中心的模型与Elastichsearch交互文档和轻松地编写一个存储库数据访问层。
  • Spring Data ElasticSearch官方文档

1 SDES入门

1.2 导入坐标

<dependencies>
    <!--es-->
    <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.apache.logging.log4j</groupId>
        <artifactId>log4j-to-slf4j</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.24</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>


    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.1</version>
    </dependency>

    <!--springdata-->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-elasticsearch</artifactId>
        <version>3.0.5.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.elasticsearch.plugin</groupId>
                <artifactId>transport-netty4-client</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.4.RELEASE</version>
    </dependency>

</dependencies>

1.2 创建applicationContext.xml

  • <font color="red">引入elasticsearch命名空间</font>
<?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:context="http://www.springframework.org/schema/context"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="
        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
        http://www.springframework.org/schema/data/elasticsearch
        http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
        ">
    <!-- 扫描Dao(repositories)包,自动创建实例 -->
    <elasticsearch:repositories base-package="com.ruki.es.repositories" />

    <!-- 扫描Service包,创建Service的实体,可以没有,有repositories就够了 -->
    <context:component-scan base-package="com.ruki.es.service"/>

    <elasticsearch:transport-client id="esClient" cluster-name="my-elasticsearch"
        cluster-nodes="127.0.0.1:9300,127.0.0.1:9301,127.0.0.1:9302"/>

    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="esClient" />
    </bean>
</beans>

1.3 编写配置实体类

  • Article
@Document(indexName = "sdes_blog", type = "article")
public class Article {
    @Id
    @Field(type = FieldType.Long, store = true)
    private long id;
    @Field(type = FieldType.text, store = true, analyzer = "ik_smart")
    private String title;
    @Field(type = FieldType.text, store = true, analyzer = "ik_smart")
    private String content;

    //getter setter

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
  1. @Document(indexName="blob3",type="article")

    1. indexName:索引的名称(必填项)
    2. type:索引的类型
  2. @Id:主键的唯一标识
  3. @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.text)

    1. index:是否设置分词
    2. analyzer:存储时使用的分词器
    3. searchAnalyze:搜索时使用的分词器
    4. store:是否存储
    5. type: 数据类型

1.4 编写Dao

  • ArticleRepository
  • <font color="red">需要继承ElasticsearchRepository<T, ID></font>,<实体泛型,ID类型>
package com.ruki.es.repositories;

import com.ruki.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;


import java.util.List;

public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
    public List<Article> findByTitle(String title);
    public List<Article> findByTitleOrContent(String title, String content);
    public List<Article> findByTitleOrContent(String title, String content, Pageable pageable);
}

1.5 编写service(可以不编写)

  • 由于在applicationContext.xml中设置了<elasticsearch:repositories base-package="com.ruki.es.repositories" />,可以不编写service,直接使用articleRepository进行常规CRUD操作,也可以遵循方法命名规则,自定义方法进行操作。
public interface ArticleService {

    public void save(Article article);
    
}
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    public void save(Article article) {
        articleRepository.save(article);
    }

}

1.6 创建测试类

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

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    
    //1. elasticsearchTemplate
    //1.1 创建索引
    //1.2 配置映射关系
    
    //2. articleRepository
    //2.1 添加文档
    //2.2 删除文档
    //2.3 查询全部
    //2.4 根据id查询
    //2.5 自定义方法查询
}

1.6.1 elasticsearchTemplate

1.6.1.1 创建索引/配置映射关系
@Test
public void testCreateIndex() {
    //创建索引,并配置映射关系
    elasticsearchTemplate.createIndex(Article.class);
    // 配置映射关系
    elasticsearchTemplate.putMapping(Article.class);
}

1.6.2 articleRepository

ArticleRepository的父类
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
    <S extends T> S save(S var1);

    <S extends T> Iterable<S> saveAll(Iterable<S> var1);

    Optional<T> findById(ID var1);

    boolean existsById(ID var1);

    Iterable<T> findAll();

    Iterable<T> findAllById(Iterable<ID> var1);

    long count();

    void deleteById(ID var1);

    void delete(T var1);

    void deleteAll(Iterable<? extends T> var1);

    void deleteAll();
}
自定义查询规则
关键字命名规则解释示例
andfindByField1AndField2根据Field1和Field2获得数据findByTitleAndContent
orfindByField1OrField2根据Field1或Field2获得数据findByTitleOrContent
isfindByField根据Field获得数据findByTitle
notfindByFieldNot根据Field获得补集数据findByTitleNot
betweenfindByFieldBetween获得指定范围的数据findByPriceBetween
lessThanEqualfindByFieldLessThan获得小于等于指定值的数据findByPriceLessThan
1.6.2.1 添加文档 save
@Test
public void addDocument() {
    for (int i = 3; i < 10; i++) {
        Article article = new Article();
        article.setId(i);
        article.setTitle(i + "Maven项目对象模型(POM)");
        article.setContent(i + "可以通过一小段描述信息来管理项目的构建,报告和文档的项目管理工具软件。Maven 除了以程序构建能力为特色之外,还提供高级项目管理工具。");
        articleRepository.save(article);
    }
}
1.6.2.2 删除文档 deleteById
@Test
public void deleteDocument() {
    articleRepository.deleteById(2l);
}
1.6.2.3 查询全部 findAll
@Test
public void findAll() {
    Iterable<Article> articles = articleRepository.findAll();
    articles.forEach(a -> System.out.println(a));
}
1.6.2.4 根据id查询 findById
@Test
public void findById() {
    Optional<Article> optional = articleRepository.findById(3l);
    if (optional != null) {
        Article article = optional.get();
        System.out.println(article);
    }
}
1.6.2.5 自定义方法查询 findByTitle
//自定义方法查询
@Test
public void testFindByTitle() {
    List<Article> list = articleRepository.findByTitle("项目");
    list.stream().forEach(a -> System.out.println(a));
}

@Test
public void testFindByTitleOrContent() {
    //没有分页查询
    //        List<Article> list = articleRepository.findByTitleOrContent("项目", "构建");
    //分页查询
    Pageable pageable = PageRequest.of(0,5);
    List<Article> list = articleRepository.findByTitleOrContent("项目", "构建", pageable);
    list.stream().forEach(a -> System.out.println(a));
}
1.6.2.6 使用原生查询对象进行查询
@Test
public void testNativeSearchQuery() {
    NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
        .withQuery(QueryBuilders.queryStringQuery("maven是一个构建工具").defaultField("title"))//设置查询条件
        .withPageable(PageRequest.of(0, 5))//设置分页
        .build();//构建查询对象
    List<Article> articles = elasticsearchTemplate.queryForList(nativeSearchQuery, Article.class);
    articles.stream().forEach(a -> System.out.println(a));
}
Last modification:December 25th, 2019 at 11:34 am