ES06-SpringData集成

ES06-SpringData集成

文章目录

  • ES06-SpringData集成
  • 1-参考网址
  • 2-知识整理
  • 3-Spring Data Elasticsearch 9.0.0 完整示例
  • 4-知识补充
    • 1-Elasticsearch JAVA操作有三种客户端:
      • 1. TransportClient(已废弃)
      • 2. JestClient(第三方 HTTP 客户端)
      • 3. RestClient(官方推荐)
      • 总结


1-参考网址

  • 【推荐】SpringData集成代仓库:https://gitee.com/enzoism/springboot-springdata-es
  • 【不推荐】RestHighLevelClient集成代码仓库:https://gitee.com/enzoism/springboot-es
  • RestHighLevelClient对接:https://blog.csdn.net/weixin_45690436/article/details/109027610

2-知识整理

  • 1)如何选择接入框架:ES7.0之后就不要再用RestHighLevelClient(2025-09-06目前公司的项目还是这种对接方式)
  • 2)后续推荐使用【Java API Client(8.x 最新)】+【SpringData】
  • 3)spring-boot-starter-data-elasticsearch代码对接示例

3-Spring Data Elasticsearch 9.0.0 完整示例

编写时间:2025-09-06,项目是【Elasticsearch 9.0.0】+【JDK17】

项目基于 Spring Boot 3.2.x + Elasticsearch 9.0.0(服务器端)+ Spring Data Elasticsearch 5.2.x
(客户端)的完整可运行示例,实现对你提供的 index_popyu 索引的 增删改查 逻辑。
(Spring Data Elasticsearch 在底层已自动使用官方推荐的 Java API Client,无需额外引入 TransportClient/JestClient。)


一、依赖与版本

<!-- pom.xml 核心片段 -->
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.5</version>
</parent><properties>
<java.version>17</java.version>
</properties><dependencies>
<!-- Spring Data Elasticsearch 5.2.x 已适配 ES 9.0 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 其他常规 starter -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
</dependencies>

二、YAML 配置

# application.yml
spring:elasticsearch:uris: http://localhost:9200      # 9.0 默认端口username:                        # 如未开启 x-pack 可留空password:

三、实体类(与 mapping 一一对应)

package com.example.es.entity;import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.*;@Document(indexName = "index_popyu")
@Setting(replicas = 0, shards = 1)   // 开发阶段简化
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UsrDoc {@Id@Field(type = FieldType.Keyword)private String usrId;@Field(type = FieldType.Text)private String usrNm;@Field(type = FieldType.Integer)private Integer usrAge;@Field(type = FieldType.Keyword)private String usrCity;@Field(type = FieldType.Keyword)private String usrPhone;@Field(type = FieldType.Date, format = DateFormat.date)private String joinDate;   // yyyy-MM-dd@Field(type = FieldType.Date, format = DateFormat.hour_minute_second)private String joinTime;   // HH:mm:ss
}

四、Repository 接口(自带 CRUD)

package com.example.es.repo;import com.example.es.entity.UsrDoc;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;@Repository
public interface UsrRepository extends ElasticsearchRepository<UsrDoc, String> {// 可按需追加自定义方法,Spring Data 会帮你生成实现
}

五、Service 层(完整增删改查)

package com.example.es.service;import com.example.es.entity.UsrDoc;
import com.example.es.repo.UsrRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;import java.util.Optional;@Service
@RequiredArgsConstructor
public class UsrService {private final UsrRepository repo;/* ---------- 增 ---------- */public UsrDoc save(UsrDoc doc) {return repo.save(doc);}/* ---------- 删 ---------- */public void deleteById(String usrId) {repo.deleteById(usrId);}/* ---------- 改 ---------- */public UsrDoc update(UsrDoc doc) {// Spring Data 的 save 根据 @Id 存在即覆盖return repo.save(doc);}/* ---------- 查 ---------- */public Optional<UsrDoc> findById(String usrId) {return repo.findById(usrId);}public Page<UsrDoc> findAll(Pageable pageable) {return repo.findAll(pageable);}
}

六、Controller(REST 入口)

package com.example.es.controller;import com.example.es.entity.UsrDoc;
import com.example.es.service.UsrService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/usr")
@RequiredArgsConstructor
public class UsrController {private final UsrService service;@PostMappingpublic UsrDoc create(@RequestBody UsrDoc doc) {return service.save(doc);}@GetMapping("/{usrId}")public ResponseEntity<UsrDoc> get(@PathVariable String usrId) {return service.findById(usrId).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());}@GetMappingpublic Page<UsrDoc> list(@PageableDefault(size = 10) Pageable pageable) {return service.findAll(pageable);}@PutMapping("/{usrId}")public UsrDoc update(@PathVariable String usrId,@RequestBody UsrDoc doc) {doc.setUsrId(usrId);   // 确保主键一致return service.update(doc);}@DeleteMapping("/{usrId}")public void delete(@PathVariable String usrId) {service.deleteById(usrId);}
}

七、启动类


@SpringBootApplication
public class Es900Application {public static void main(String[] args) {SpringApplication.run(Es900Application.class, args);}
}

八、验证

  1. 启动 Elasticsearch 9.0.0(默认端口 9200)。
  2. 启动 Spring Boot,首次访问任意接口时,Spring Data 会自动根据 @Document 注解创建 index_popyu 并写入你给出的
    mapping(已内置)。
  3. 使用 curl / Postman 调用:
POST http://localhost:8080/usr
{"usrId": "u001","usrNm": "Popyu","usrAge": 18,"usrCity": "shenzhen","usrPhone": "13800138000","joinDate": "2025-09-06","joinTime": "14:30:00"
}
GET  http://localhost:8080/usr/u001
PUT  http://localhost:8080/usr/u001
DEL  http://localhost:8080/usr/u001

4-知识补充

1-Elasticsearch JAVA操作有三种客户端:

1、TransportClient
2、JestClient
3、RestClient

在 Elasticsearch 7.x 之后,TransportClient 已被废弃,官方推荐使用 RestHighLevelClient(基于 RestClient 封装)或最新的 Java API Client(Elasticsearch 8.x 推出)。以下是三种客户端的对比和示例:


1. TransportClient(已废弃)

  • 特点:基于 TCP 协议,直接连接集群节点,性能高但依赖 ES 版本。
  • 缺点:兼容性差(需与集群版本一致),7.x 后废弃。
  • 示例(不推荐):
    // 已废弃,无需关注
    

2. JestClient(第三方 HTTP 客户端)

  • 特点:基于 HTTP 协议,轻量级,支持版本兼容性较好。
  • 缺点:功能有限,更新滞后(非官方维护)。
  • 依赖
    <dependency><groupId>io.searchbox</groupId><artifactId>jest</artifactId><version>6.3.1</version>
    </dependency>
    
  • 示例
    JestClientFactory factory = new JestClientFactory();
    factory.setHttpClientConfig(new HttpClientConfig.Builder("http://localhost:9200").multiThreaded(true).build());
    JestClient client = factory.getObject();// 索引文档
    Index index = new Index.Builder("{\"name\":\"John\"}").index("users").type("_doc").build();
    client.execute(index);
    

3. RestClient(官方推荐)

  • 特点:基于 HTTP 协议,官方维护,支持所有 ES 功能。
  • 分类
    • RestLowLevelClient:轻量级,需手动处理请求/响应。
    • RestHighLevelClient(7.x 常用):封装了高级 API(已废弃)。
    • Java API Client(8.x 最新):官方推荐,基于 REST 协议。
  • 示例(RestHighLevelClient,7.x)
    RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );// 索引文档
    IndexRequest request = new IndexRequest("users");
    request.source("{\"name\":\"John\"}", XContentType.JSON);
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    
  • 示例(Java API Client,8.x)
    ElasticsearchClient client = new ElasticsearchClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))
    );// 索引文档
    IndexRequest<User> request = IndexRequest.of(i -> i.index("users").document(new User("John"))
    );
    client.index(request);
    

总结

客户端协议状态适用场景
TransportClientTCP已废弃
JestClientHTTP非官方维护轻量级需求(不推荐)
RestClientHTTP官方推荐所有新版本(7.x/8.x)

建议

  • 7.x:使用 RestHighLevelClient(已废弃但可用)。
  • 8.x:迁移到 Java API Client(基于 REST,官方支持)。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/98343.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/98343.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

对于链表相关经典算法题:环形链表的约瑟夫问题的解析

开篇介绍&#xff1a; Hello 大家&#xff0c;在上一篇博客中&#xff0c;我们一同拆解了「206. 反转链表」和「876. 链表的中间结点」这两道单链表经典题目&#xff0c;通过对指针操作的细致打磨&#xff0c;相信大家对单链表的特性与算法设计思路有了更深入的理解。而在今天…

MySQL集群——主从复制

目录 一、环境搭建、部署 1. RHEL7.9、9.3的搭建 二、主从复制 1. 环境说明 2. 环境准备 1&#xff09;克隆RHEL79_mysql_master 2&#xff09;改名为 “RHEL79_mysql_slave” 并修改IP 3&#xff09;修改主机名 3. 部署MySQL主从同步 1&#xff09;主库(mysql-master) 2&…

《用 asyncio 构建异步任务队列:Python 并发编程的实战与思考》

《用 asyncio 构建异步任务队列:Python 并发编程的实战与思考》 一、引言:并发编程的新时代 在现代软件开发中,性能已不再是锦上添花,而是产品成功的基石。尤其在 I/O 密集型场景中,如网络爬虫、实时数据处理、微服务通信等,传统的同步编程模式往往力不从心。 Python …

【Linux】yum工具篇

目录一、软件包管理器1.1 什么是软件包1.2 Linux软件生态二、yum具体操作2.1 查找软件包2.2 安装软件包2.3 卸载软件配置文件所在路径个人主页<—请点击 Linux专栏<—请点击 一、软件包管理器 1.1 什么是软件包 在Linux下安装软件, 一个通常的办法是下载到程序的源代码…

撬动制造全场景增效,开利空调找到了怎样的“通关密码”?

由深圳软件协会指导、法大大和信息侠联合出品的《制造行业合同数智化升级白皮书》&#xff08;以下简称“白皮书”&#xff09;首次提出了 “电子签法律AI” 双轮驱动模型。在制造行业面临供应链协同、合规风控及全球化出海等多重挑战的当下&#xff0c;法大大依托丰富的制造企…

[Android]RecycleView的item用法

RecyclerView 是 Android 提供的一个强大的列表控件&#xff0c;用来显示大量数据。RecyclerView 的主要特点 1. 高性能的视图复用机制 Recycle就是循环的意思&#xff0c;那么recycleview的特点也很鲜明了&#xff0c;它只会创建出在屏幕内和一定缓存的itemview,当view滑出屏幕…

AI驱动的软件测试:革命性的自动化、缺陷检测与实验优化

引言在当今快节奏的软件开发生命周期&#xff08;SDLC&#xff09;中&#xff0c;传统测试方法已逐渐无法满足对速度、覆盖面和准确性的极高要求。人工智能&#xff08;AI&#xff09;和机器学习&#xff08;ML&#xff09;技术的融入&#xff0c;正在从根本上重塑软件测试的格…

继续优化基于树状数组的cuda前缀和

在之前的博客《借助树状数组的思想实现cuda版前缀和》中&#xff0c;我们用三个kernel实现了基于树状数组的cuda版前缀和&#xff0c;但是在数据量较大时速度不如传统的reduce-then-scan方法&#xff0c;主要原因在于跨block的reduce阶段没有充分利用所有的cuda核心。在本博客中…

Qt图片资源导入

右键项目&#xff0c;点击添加新文件 选择Qt -> Qt Resource File 资源文件起名 如&#xff1a;res 生成res.qrc文件 在项目的同级目录下创建文件夹res&#xff0c;并将准备好的资源粘贴进去 右键qrc文件&#xff0c;选中Open in Editor 添加前缀 前缀是各种类型图片的分类&…

嵌入式第四十六天(51单片机(中断,定时器))

一.独立按键设置1.#include "key.h"void init_key(void) {P1 | (0x0F << 4); }int key_pressed(void) {static int ret 0;if((P1 & (1 << 4)) 0){ret 1;}else if((P1 & (1 << 5)) 0){ret 2;}else if((P1 & (1 << 6)) 0){r…

Visual Studio Code2024安装包及安装教程

一、软件下载软件名称&#xff1a;Visual Studio Code 2024安装环境&#xff1a;window10及以上系统下载链接&#xff1a;https://pan.quark.cn/s/d9831b28c69a解压软件Bandizip下载链接&#xff1a;https://pan.quark.cn/s/a54e79b5d553二、软件安装1、下载后&#xff0c;先解…

fps:游戏玩法

能帮到你的话&#xff0c;就给个赞吧 &#x1f618; 文章目录游戏玩法倒计时僵尸潮游戏成功&失败计时玩法&#xff1a;玩家在计时内存活&#xff0c;成功&#xff1b;反之失败Game界面&#xff1a;由关卡调用计时系统计时完成&#xff1a;调用结果界面结果界面玩家死亡&…

如何建立针对 .NET Core web 程序的线程池的长期监控

如何建立针对 .NET Core web 程序的线程池的长期监控 建立针对 .NET Core Web 应用程序线程池的长期监控是一个系统性的工程&#xff0c;它涉及代码集成、指标收集、存储、可视化和告警。 核心思路 线程池监控不是孤立的&#xff0c;它必须与应用程序的整体性能指标&#xff08…

前端开发学习路径

前端开发学习路径前端开发基础技能HTML、CSS和JavaScript是前端开发的三大核心技术。HTML用于构建网页结构&#xff0c;CSS负责样式设计&#xff0c;JavaScript实现交互功能。掌握这三项技术是学习前端开发的基础。现代前端开发通常需要了解ES6语法&#xff0c;包括箭头函数、解…

一款没有任何限制的免费远程手机控制手机的软件简介

这是一款没有任何限制的免费远程手机控制手机的软件支持安卓和苹果1.安装1.1被控制端安装airdroid1.2控制端air mirror2.登录同一个账号3.控制使用打开控制端软件选择要控制的机器直接点“远程控制“连接上后就可以任意操作被控手机了

在word中使用lateX公式的方法

非常好的问题&#xff01;这是一个许多科研人员和学生都渴望实现的功能。但需要明确的是&#xff1a; **Microsoft Word 本身并不具备“自动”将 LaTeX 代码实时转换为渲染后公式的功能。** 它不像 Overleaf 或 VS Code 的 Markdown 插件那样&#xff0c;输入 $Emc^2$ 就立刻变…

23种设计模式——代理模式(Proxy Pattern)详解

✅作者简介&#xff1a;大家好&#xff0c;我是 Meteors., 向往着更加简洁高效的代码写法与编程方式&#xff0c;持续分享Java技术内容。 &#x1f34e;个人主页&#xff1a;Meteors.的博客 &#x1f49e;当前专栏&#xff1a;设计模式 ✨特色专栏&#xff1a;知识分享 &#x…

webpack scope hositing 和tree shaking

Scope Hoisting&#xff08;作用域提升&#xff09; 和 Tree Shaking&#xff08;摇树优化&#xff09; 是现代前端构建中至关重要的概念。它们是构建工具&#xff08;如 Webpack、Rollup、Vite&#xff09;用来优化最终打包产物的核心技术。 核心概念快速理解 Tree Shaking&am…

手写React状态hook

在日常开发中&#xff0c;我们经常用到 React 的状态管理 Hook&#xff1a;useState 和 useReducer。 但你有没有想过&#xff1a;这些 Hook 内部是怎么实现的&#xff1f;为什么调用 setState 之后组件会重新渲染&#xff1f; 今天我们就来从零手写 useState 和 useReducer&am…

力扣hot100:相交链表与反转链表详细思路讲解(160,206)

问题描述核心思路&#xff1a;双指针交替遍历算法思想&#xff1a; 使用两个指针 pa 和 pb 分别从链表A和链表B的头节点出发&#xff0c;同步向后遍历。当任一指针走到链表末尾时&#xff0c;将其重定位到另一链表的头节点继续遍历。若两链表相交&#xff0c;pa 和 pb 最终会在…