SpringBoot 整合 ES 实现 CRUD 操作

本文介绍如何在Spring Boot项目中集成Elasticsearch并实现数据的增删查改,包括分页和滚动查询。通过示例代码演示了ElasticsearchRepository、ElasticsearchRestTemplate和ElasticsearchOperations的使用,并讨论了深度分页与滚动查询的性能差异。
摘要由CSDN通过智能技术生成

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值