本节讲解SpringBoot与Spring-data-elasticsearch整合的入门案例。

一、环境搭建

新建maven项目,名字随意

pom.xml

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.3.1.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-web</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-test</artifactId>
  18. </dependency>
  19. </dependencies>

application.yml

  1. spring:
  2. data:
  3. elasticsearch: #ElasticsearchProperties
  4. cluster-name: elasticsearch #默认即为elasticsearch
  5. cluster-nodes: 120.25.194.233:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode

这些配置的属性,最终会设置到org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchProperties这个实体中。

二、创建实体

Spring-data-elasticsearch为我们提供了@Document@Field等注解,如果某个实体需要建立索引,只需要加上这些注解即可。例如以一个文章实体为例:

Article.java

  1. import java.io.Serializable;
  2. import java.util.Date;
  3. import org.springframework.data.annotation.Id;
  4. import org.springframework.data.elasticsearch.annotations.DateFormat;
  5. import org.springframework.data.elasticsearch.annotations.Document;
  6. import org.springframework.data.elasticsearch.annotations.Field;
  7. @Document(indexName="article_index",type="article",shards=5,replicas=1,indexStoreType="fs",refreshInterval="-1")
  8. public class Article implements Serializable{
  9. /**
  10. *
  11. */
  12. private static final long serialVersionUID = 551589397625941750L;
  13. @Id
  14. private Long id;
  15. /**标题*/
  16. private String title;
  17. /**摘要*/
  18. private String abstracts;
  19. /**内容*/
  20. private String content;
  21. /**发表时间*/
  22. @Field(format=DateFormat.date_time,index=FieldIndex.no,store=true,type=FieldType.Object)
  23. private Date postTime;
  24. /**点击率*/
  25. private Long clickCount;
  26. //setters and getters
  27. //toString
  28. }

在需要建立索引的类上加上@Document注解,即表明这个实体需要进行索引。其定义如下:

  1. @Persistent
  2. @Inherited
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Target({ElementType.TYPE})
  5. public @interface Document {
  6. String indexName();//索引库的名称,个人建议以项目的名称命名
  7. String type() default "";//类型,个人建议以实体的名称命名
  8. short shards() default 5;//默认分区数
  9. short replicas() default 1;//每个分区默认的备份数
  10. String refreshInterval() default "1s";//刷新间隔
  11. String indexStoreType() default "fs";//索引文件存储类型
  12. }

加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词。

我们通过@Field注解来进行详细的指定,如果没有特殊需求,那么只需要添加@Document即可。在我们的案例中,使用了@Field针对日期属性postTime上进行了指定。

@Field注解的定义如下:

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.FIELD)
  3. @Documented
  4. @Inherited
  5. public @interface Field {
  6. FieldType type() default FieldType.Auto;#自动检测属性的类型
  7. FieldIndex index() default FieldIndex.analyzed;#默认情况下分词
  8. DateFormat format() default DateFormat.none;
  9. String pattern() default "";
  10. boolean store() default false;#默认情况下不存储原文
  11. String searchAnalyzer() default "";#指定字段搜索时使用的分词器
  12. String indexAnalyzer() default "";#指定字段建立索引时指定的分词器
  13. String[] ignoreFields() default {};#如果某个字段需要被忽略
  14. boolean includeInParent() default false;
  15. }

需要注意的是,这些默认值指的是我们没有在我们没有在属性上添加@Filed注解的默认处理。一旦添加了@Filed注解,所有的默认值都不再生效。此外,如果添加了@Filed注解,那么type字段必须指定。

三 创建Repository

我们只要编写一个接口ArticleSearchRepository,来继承Spring-data-elasticSearch提供的ElasticsearchRepository即可。

  1. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  2. import spring.data.elasticsearch.docs.Article;
  3. //泛型的参数分别是实体类型和主键类型
  4. public interface ArticleSearchRepository extends ElasticsearchRepository<Article, Long>{
  5. }

四、编写测试类

1、测试自动创建mapping

ArticleSearchRepositoryTest.java

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringApplicationConfiguration(classes=Application.class)
  3. public class ArticleSearchRepositoryTest {
  4. @Autowired
  5. private ArticleSearchRepository articleSearchRepository;
  6. @Test
  7. public void test(){
  8. System.out.println("演示初始化");
  9. }
  10. }

这个测试仅仅是为了演示应用启动后,Spring-data-elasticSearch会自动帮我们建立索引库和创建实体的mapping信息。

当成功启动之后,通过sense控制台查看映射信息

可以右边的结果中,的确出现了article的,mapping信息。

默认情况下,在创建mapping信息的时候,只会创建添加了@Field注解的mapping信息。其他没有添加@Filed注解的字段在保存索引的时候自动确定。

需要注意的是,mapping信息可以自动创建,但是不能自动更新,也就是说,如果需要重新进行mapping映射的话,需要将原来的删除,再进行mapping映射。读者可以尝试一下将postTime的type改为FieldType.long,这种情况下,会自动将日期转换成时间戳。但是mapping信息不会自动更新,必须将原有的mapping信息删除之后,才能重新建立映射。

2、测试保存

  1. @Test
  2. public void testSave(){
  3. Article article=new Article();
  4. article.setId(1L);
  5. article.setTitle("elasticsearch教程");
  6. article.setAbstracts("spring-data-elastichSearch");
  7. article.setContent("SpringBoot与spring-data-elastichSearch整合");
  8. article.setPostTime(new Date());
  9. article.setClickCount(100l);
  10. articleSearchRepository.save(article);
  11. }

运行程序后,我们首先查看mapping信息有没有自动创建

此时查看创建的索引结果

 
 
 http://www.tianshouzhi.com/api/tutorials/elasticsearch/159

限定查询结果集大小

Spring Data允许开发者使用firsttop关键字对返回的查询结果集大小进行限定。fisrt和top需要跟着一个代表返回的结果集的最大大小的数字。如果没有跟着一个数字,那么返回的结果集大小默认为1。

Example 8.Limiting the result size of query with Top and First(利用first和top限制返回的结果集大小)

User findFirstByOrderByLastnameAsc();

User findTopByOrderByAgeDesc();

Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

Slice<User> findTop3ByLastname(String lastname, Pageable pageable);

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);

限制结果集的表达式还支持Distinct关键字。并且,当返回的结果集大小限制为1时,Spring Data支持将返回结果包装到Optional(java 8新增,这是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象)之中,例子如下:

Optional<User> findFirstByOrderByLastnameAsc();

在查询用page和slice来进行分页查询的情况下,同样可以使用firsttop来对结果集大小进行限制。

+

注意,如果在使用Sort参数对查询结果进行排序的基础上加上对结果集大小的限制,就可以轻易的获得最大的K个元素或最小的K个元素。

https://es.yemengying.com/4/4.4/4.4.5.html

5.1 入门整合案例(SpringBoot+Spring-data-elasticsearch) ---- good的更多相关文章

  1. SpringBoot整合Spring Data Elasticsearch

    Spring Data Elasticsearch提供了ElasticsearchTemplate工具类,实现了POJO与elasticsearch文档之间的映射 elasticsearch本质也是存 ...

  2. Springboot spring data jpa 多数据源的配置01

    Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库   global 数据库 ...

  3. springboot集成spring data ElasticSearch

    ES支持SpringBoot使用类似于Spring Data Jpa的方式查询,使得查询更加方便. 1.依赖引入 compile “org.springframework.boot:spring-bo ...

  4. 3.4_springboot2.x整合spring Data Elasticsearch

    Spring Data Elasticsearch 是spring data对elasticsearch进行的封装. 这里有两种方式操作elasticsearch: 1.使用Elasticsearch ...

  5. SprignBoot整合Spring Data Elasticsearch

    一.原生java整合elasticsearch的API地址 https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.2/java ...

  6. Spring Boot + Spring Data + Elasticsearch实例

    Spring Boot + Spring Data + Elasticsearch实例 学习了:https://blog.csdn.net/huangshulang1234/article/detai ...

  7. 031 Spring Data Elasticsearch学习笔记---重点掌握第5节高级查询和第6节聚合部分

    Elasticsearch提供的Java客户端有一些不太方便的地方: 很多地方需要拼接Json字符串,在java中拼接字符串有多恐怖你应该懂的 需要自己把对象序列化为json存储 查询到结果也需要自己 ...

  8. Spring Data ElasticSearch的使用

    1.什么是Spring Data Spring Data是一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务. S ...

  9. elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

    一.ES Client 简介 1. ES是一个服务,采用C/S结构 2. 回顾 ES的架构 3. ES支持的客户端连接方式 3.1 REST API ,端口 9200 这种连接方式对应于架构图中的RE ...

随机推荐

  1. Loadrunner--Analysis网页细分图

    续LR实战之Discuz开源论坛项目,之前一直是创建虚拟用户脚本(Virtual User Generator)和场景(Controller),现在,终于到了LoadRunner性能测试结果分析(An ...

  2. Java Lock Example – ReentrantLock(java锁的例子)

    Welcome to Java Lock example tutorial. Usually when working with multi-threaded environment, we use ...

  3. startActivityForResult()方法具体解释

    我们都知道.要开启一个Activity能够在上下文环境中调用startActivity()方法. 可是假设想从开启的Activity中获取某些数据,就能够使用startActivityForResul ...

  4. 9.8 Binder系统_c++实现_内部机制1

    1. 内部机制_回顾binder框架关键点 binder进程通讯过程情景举例: test_server通过addservice向service_manager注册服务 test_client通过get ...

  5. SoC编译HEX脚本(基于RISC-V的SoC)

    SoC编译HEX脚本(基于RISC-V的SoC) 脚本使用 ./compile hello 脚本:设置RISC-V工具链riscv_set_env ############## RISC-V #### ...

  6. [Nuxt] Use Vuex Actions to Delete Data from APIs in Nuxt and Vue.js

    You'll begin to notice as you build out your actions in Vuex, many of them will look quite similar. ...

  7. spark 编程教程

      参考: 英文:https://spark.apache.org/docs/latest/programming-guide.html 中文:http://www.cnblogs.com/lujin ...

  8. Maven基础教程 分类: C_OHTERS 2015-04-10 22:53 232人阅读 评论(0) 收藏

    更多内容请参考官方文档:http://maven.apache.org/guides/index.html 官方文档很详细,基本上可以查找到一切相关的内容. 另外,快速入门可参考视频:孔浩的maven ...

  9. sql海量数据优化

    1.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null 可以在num上设 ...

  10. WM_CAP_DRIVER_CONNECT

    WM_CAP_DRIVER_CONNECT //ActiveX ---->OnCreate m_pit.Create(IDD_CAM_DIALOG,this);  CRect rc;  this ...