5.1 入门整合案例(SpringBoot+Spring-data-elasticsearch) ---- good
本节讲解SpringBoot与Spring-data-elasticsearch整合的入门案例。
一、环境搭建
新建maven项目,名字随意
pom.xml
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.3.1.RELEASE</version>
- </parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- </dependency>
- </dependencies>
application.yml
- spring:
- data:
- elasticsearch: #ElasticsearchProperties
- cluster-name: elasticsearch #默认即为elasticsearch
- cluster-nodes: 120.25.194.233:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
这些配置的属性,最终会设置到org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchProperties这个实体中。
二、创建实体
Spring-data-elasticsearch为我们提供了@Document、@Field等注解,如果某个实体需要建立索引,只需要加上这些注解即可。例如以一个文章实体为例:
Article.java
- import java.io.Serializable;
- import java.util.Date;
- import org.springframework.data.annotation.Id;
- import org.springframework.data.elasticsearch.annotations.DateFormat;
- import org.springframework.data.elasticsearch.annotations.Document;
- import org.springframework.data.elasticsearch.annotations.Field;
- @Document(indexName="article_index",type="article",shards=5,replicas=1,indexStoreType="fs",refreshInterval="-1")
- public class Article implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 551589397625941750L;
- @Id
- private Long id;
- /**标题*/
- private String title;
- /**摘要*/
- private String abstracts;
- /**内容*/
- private String content;
- /**发表时间*/
- @Field(format=DateFormat.date_time,index=FieldIndex.no,store=true,type=FieldType.Object)
- private Date postTime;
- /**点击率*/
- private Long clickCount;
- //setters and getters
- //toString
- }
在需要建立索引的类上加上@Document注解,即表明这个实体需要进行索引。其定义如下:
- @Persistent
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.TYPE})
- public @interface Document {
- String indexName();//索引库的名称,个人建议以项目的名称命名
- String type() default "";//类型,个人建议以实体的名称命名
- short shards() default 5;//默认分区数
- short replicas() default 1;//每个分区默认的备份数
- String refreshInterval() default "1s";//刷新间隔
- String indexStoreType() default "fs";//索引文件存储类型
- }
加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词。
我们通过@Field注解来进行详细的指定,如果没有特殊需求,那么只需要添加@Document即可。在我们的案例中,使用了@Field针对日期属性postTime上进行了指定。
@Field注解的定义如下:
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.FIELD)
- @Documented
- @Inherited
- public @interface Field {
- FieldType type() default FieldType.Auto;#自动检测属性的类型
- FieldIndex index() default FieldIndex.analyzed;#默认情况下分词
- DateFormat format() default DateFormat.none;
- String pattern() default "";
- boolean store() default false;#默认情况下不存储原文
- String searchAnalyzer() default "";#指定字段搜索时使用的分词器
- String indexAnalyzer() default "";#指定字段建立索引时指定的分词器
- String[] ignoreFields() default {};#如果某个字段需要被忽略
- boolean includeInParent() default false;
- }
需要注意的是,这些默认值指的是我们没有在我们没有在属性上添加@Filed注解的默认处理。一旦添加了@Filed注解,所有的默认值都不再生效。此外,如果添加了@Filed注解,那么type字段必须指定。
三 创建Repository
我们只要编写一个接口ArticleSearchRepository,来继承Spring-data-elasticSearch提供的ElasticsearchRepository即可。
- import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
- import spring.data.elasticsearch.docs.Article;
- //泛型的参数分别是实体类型和主键类型
- public interface ArticleSearchRepository extends ElasticsearchRepository<Article, Long>{
- }
四、编写测试类
1、测试自动创建mapping
ArticleSearchRepositoryTest.java
- @RunWith(SpringJUnit4ClassRunner.class)
- @SpringApplicationConfiguration(classes=Application.class)
- public class ArticleSearchRepositoryTest {
- @Autowired
- private ArticleSearchRepository articleSearchRepository;
- @Test
- public void test(){
- System.out.println("演示初始化");
- }
- }
这个测试仅仅是为了演示应用启动后,Spring-data-elasticSearch会自动帮我们建立索引库和创建实体的mapping信息。
当成功启动之后,通过sense控制台查看映射信息

可以右边的结果中,的确出现了article的,mapping信息。
默认情况下,在创建mapping信息的时候,只会创建添加了@Field注解的mapping信息。其他没有添加@Filed注解的字段在保存索引的时候自动确定。
需要注意的是,mapping信息可以自动创建,但是不能自动更新,也就是说,如果需要重新进行mapping映射的话,需要将原来的删除,再进行mapping映射。读者可以尝试一下将postTime的type改为FieldType.long,这种情况下,会自动将日期转换成时间戳。但是mapping信息不会自动更新,必须将原有的mapping信息删除之后,才能重新建立映射。
2、测试保存
- @Test
- public void testSave(){
- Article article=new Article();
- article.setId(1L);
- article.setTitle("elasticsearch教程");
- article.setAbstracts("spring-data-elastichSearch");
- article.setContent("SpringBoot与spring-data-elastichSearch整合");
- article.setPostTime(new Date());
- article.setClickCount(100l);
- articleSearchRepository.save(article);
- }
运行程序后,我们首先查看mapping信息有没有自动创建

此时查看创建的索引结果

限定查询结果集大小
Spring Data允许开发者使用first和top关键字对返回的查询结果集大小进行限定。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来进行分页查询的情况下,同样可以使用first和top来对结果集大小进行限制。
注意,如果在使用Sort参数对查询结果进行排序的基础上加上对结果集大小的限制,就可以轻易的获得最大的K个元素或最小的K个元素。
https://es.yemengying.com/4/4.4/4.4.5.html
5.1 入门整合案例(SpringBoot+Spring-data-elasticsearch) ---- good的更多相关文章
- SpringBoot整合Spring Data Elasticsearch
Spring Data Elasticsearch提供了ElasticsearchTemplate工具类,实现了POJO与elasticsearch文档之间的映射 elasticsearch本质也是存 ...
- Springboot spring data jpa 多数据源的配置01
Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库 global 数据库 ...
- springboot集成spring data ElasticSearch
ES支持SpringBoot使用类似于Spring Data Jpa的方式查询,使得查询更加方便. 1.依赖引入 compile “org.springframework.boot:spring-bo ...
- 3.4_springboot2.x整合spring Data Elasticsearch
Spring Data Elasticsearch 是spring data对elasticsearch进行的封装. 这里有两种方式操作elasticsearch: 1.使用Elasticsearch ...
- SprignBoot整合Spring Data Elasticsearch
一.原生java整合elasticsearch的API地址 https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.2/java ...
- Spring Boot + Spring Data + Elasticsearch实例
Spring Boot + Spring Data + Elasticsearch实例 学习了:https://blog.csdn.net/huangshulang1234/article/detai ...
- 031 Spring Data Elasticsearch学习笔记---重点掌握第5节高级查询和第6节聚合部分
Elasticsearch提供的Java客户端有一些不太方便的地方: 很多地方需要拼接Json字符串,在java中拼接字符串有多恐怖你应该懂的 需要自己把对象序列化为json存储 查询到结果也需要自己 ...
- Spring Data ElasticSearch的使用
1.什么是Spring Data Spring Data是一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务. S ...
- 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 ...
随机推荐
- Qt5 UI信号、槽自动连接的控件重名大坑(UI生成的槽函数存在一个隐患,即控件重名。对很复杂的控件,不要在 designer 里做提升,而是等到程序启动后,再动态创建,可以避免很多问题)
对Qt5稍有熟悉的童鞋都知道信号.槽的自动连接机制.该机制使得qt designer 设计的UI中包含的控件,可以不通过显式connect,直接和cpp中的相应槽相关联.该机制的详细文章见 http: ...
- 对生产者和消费者问题的另一个解决办法是使用QWaitCondition(封装好了wakeOne,wakeAll,而且与QReadWriteLock对接,几乎是万能的办法)
对生产者和消费者问题的另一个解决办法是使用QWaitCondition,它允许线程在一定条件下唤醒其他线程.其中wakeOne()函数在条件满足时随机唤醒一个等待线程,而wakeAll()函数则在条件 ...
- 【z07】机器翻译
[题目链接]:http://noi.qz5z.com/viewtask.asp?id=z07 [题解] 可以理解为一直往一个队列里面加东西: 然后每次查找一个东西在不在队列的最尾部长度为m的区间范围内 ...
- VSX(翻译)Moving Code Blocks Among Code Regions using VS 2010 Extensions
Moving Code Blocks Among Code Regions using VS 2010 Extensions (翻译)使用VS 2010 扩展性将代码块移至Region区域中 Down ...
- Android5.0(Lollipop) BLE蓝牙4.0+浅析code(二)
作者:Bgwan链接:https://zhuanlan.zhihu.com/p/23347612来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. Android5.0(L ...
- python画最最简单的折线图
# encoding=utf-8import matplotlib.pyplot as pltfrom pylab import * #支持中文mpl.rcParams['font.sans-seri ...
- 【u237】分数化小数
Time Limit: 1 second Memory Limit: 128 MB [问题描述] 写一个程序,输入一个形如N/D的分数(N是分子,D是分母),输出它的小数形式.如果小数有循环节的话,把 ...
- 选择标识符(identifier)
整数通常是标识列最好的选择,因为它们很快并且可以使用auto_increment:千万不要使用enum和set类型作为标识列:尽量避免使用字符串类型作为标识列,因为他们很消耗空间,并且通常比数字类型慢 ...
- 使用JQuery将前端form表单数据转换为JSON字符串传递到后台处理
一般地,我们在处理表单(form表单哦)数据时,传输对象或字符串到后台,Spring MVC或SpringBoot的Controller接收时使用一个对象作为参数就可以被正常接收并封装到对象中.这种方 ...
- javascript中定义事件的三种方式 分类: C1_HTML/JS/JQUERY 2014-08-07 10:27 634人阅读 评论(0) 收藏
在javascript中,可以为某个元素指定事件,指定的方式有以下三种: 1.在html中,使用onclick属性 2.在javascript中,使用onclick属性 3.在javascipt中,使 ...