当前位置: 首页 > java >正文

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.xdnf.cn/news/20372.html

相关文章:

  • Valgrind检测内存泄漏入门指南
  • ClickHouse 中的物化列与物化视图
  • SpringBoot01-配置文件
  • 未来教育行业的 Go 服务开发解决方案与实践
  • 【PyTorch实战:Tensor】4、NumPy与PyTorch Tensor指南:深度学习中的数据操作与转换
  • Python基础(①⑧Queue)
  • 机床夹具设计 +选型
  • 持续集成和持续交付 (CI/CD) 工具——Jenkins
  • `objdump`与`addr2line`工具详解
  • 新服务器初始化:Git全局配置与SSH密钥生成
  • 【Canvas与图标】古铜色“HTML”图标
  • eclipse 安装 lombok
  • 【基础-单选】下列哪一项不属于ArkUI组件的公共事件?
  • JVM调优总结
  • ECharts Gallery:Apache官方数据可视化模板库,助你快速制作交互图表并实现深度定制
  • 微服务的编程测评系统22-项目部署结束
  • 基于Echarts+HTML5可视化数据大屏展示-图书馆大屏看板
  • 软考 系统架构设计师系列知识点之杂项集萃(142)
  • JVM中如何调优新生代和老生代?
  • 基于LSTM深度学习的网络流量测量算法matlab仿真
  • C++ 内存模型:用生活中的例子理解并发编程
  • linux C 语言开发 (三) 建立云服务器
  • C++ 小游戏:拍桌子
  • Nmap网络扫描工具详细使用教程
  • 算法学习路径
  • 基于 Gemini 的 CI/CD 自动化测评 API 集成实战教程
  • Browser Use:打造你的浏览器自动化助手
  • Python数据可视化科技图表绘制系列教程(六)
  • 【Python自动化】 21 Pandas Excel 操作完整指南
  • 小杰机器学习(two)——导数、损失函数、斜率极值最值、微分规则、切平面与偏导数、梯度。