Hi,我是空夜,好久不见!
本文介绍 Spring Boot 项目中整合 ElasticSearch 并实现 CRUD 操作,包括分页、滚动等功能。
之前在公司使用 ES,一直用的是前辈封装好的包,最近希望能够从原生的 Spring Boot/ES 语法角度来学习 ES 的相关技术。希望对大家有所帮助。
本文为 spring-boot-examples 系列文章节选,示例代码已上传至 https://github.com/laolunsi/spring-boot-examples
安装 ES 与可视化工具
前往 ES 官方 https://www.elastic.co/cn/downloads/elasticsearch 进行,如 windows 版本只需要下载安装包,启动 elasticsearch.bat 文件,浏览器访问 http://localhost:9200
如此,表示 ES 安装完毕。
为更好地查看 ES 数据,再安装一下 elasticsearch-head 可视化插件。前往下载地址:https://github.com/mobz/elasticsearch-head
主要步骤:
git clone git://github.com/mobz/elasticsearch-head.git
cd elasticsearch-head
npm install
npm run start
open
http://localhost:9100/
可能会出现如下情况:
发现是跨域的问题。
解决办法是在 elasticsearch 的 config 文件夹中的 elasticsearch.yml 中添加如下两行配置:
http.cors.enabled: true
http.cors.allow-origin: "*"
刷新页面:
这里的 article 索引就是我通过 spring boot 项目自动创建的索引。
下面我们进入正题。
Spring Boot 引入 ES
创建一个 spring-boot 项目,引入 es 的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置 application.yml:
server:
port: 8060
spring:
elasticsearch:
rest:
uris: http://localhost:9200
创建一个测试的对象,article:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import java.util.Date;
@Document(indexName = "article")
public class Article {
@Id
private String id;
private String title;
private String content;
private Integer userId;
private Date createTime;
// ... igonre getters and setters
}
下面介绍 Spring Boot 中操作 ES 数据的三种方式:
- 实现 ElasticsearchRepository 接口
- 引入 ElasticsearchRestTemplate
- 引入 ElasticsearchOperations
实现对应的 Repository:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ArticleRepository extends ElasticsearchRepository<Article