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 ...
随机推荐
- echarts3.0 仪表盘实例更改完成占用率实例
需要完成的项目效果 官方实例效果 基本思路: 首先引入jquery和echarts3.0库. 需要两个仪表盘,一个仪表盘是纯色灰色,在底部.startAngle 和endAngle永远是最大值,默认为 ...
- MySQL字符编码问题,Incorrect string value
MySQL上插入汉字时报错例如以下.详细见后面分析. Incorrect string value: '\xD0\xC2\xC8A\xBEW' for column 'ctnr' at row 1 M ...
- Codeforces Round #315 (Div. 2) (ABCD题解)
比赛链接:http://codeforces.com/contest/569 A. Music time limit per test:2 seconds memory limit per test: ...
- wireshark分析包中关于三次握手和四次终止标识
转自: http://hi.baidu.com/hepeng597/item/5ba27e0b98bc8de3ff240de0 三次握手Three-way Handshake 一个虚拟连接的建立是通过 ...
- codeforces 571B--Minimization(贪心+dp)
D. Minimization time limit per test 2 seconds memory limit per test 256 megabytes input standard inp ...
- [Angular2Fire] Firebase auth (Google, Github)
To do auth, first you need to go firebase.console.com to enable the auth methods, for example, enabl ...
- 无意中发现Markdown,最终解放了我
文件夹 概述 换行 删除线 链接自己主动识别 表格 代码块高亮 定义列表 脚注 自己主动生成文件夹 參考资料 正文 概述 大部分情况下,Markdown的基本的语法已够我们使用,比方随性记录点东西.非 ...
- iOS将汉字转换为拼音
将汉字转换为拼音 - (NSString *)chineseToPinyin:(NSString *)chinese withSpace:(BOOL)withSpace { CFStringRef h ...
- Emmet超详细教程
Emmet超详细教程 一.总结 一句话总结:用的时候照着用,能提高效率. 1.快捷键如何使用? 需要敲代码的时候把快捷键放到旁边即可.照着敲. 二.Emmet超详细教程 Emmet的前身是大名鼎鼎的Z ...
- HTML5开发移动web应用——SAP UI5篇(9)
之前我们对于app的构建都是基于显示的.如今我们来格式化一下,引入很多其它的SAP UI5组件概念.这使得APP的一个界面更有层次性.更像是一个手机应用的界面,而且更好地使用SAP UI5中提供的功能 ...