ES06-SpringData集成
ES06-SpringData集成
ES06-SpringData集成
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;
@PostMapping
public 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());
}
@GetMapping
public 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);
}
}
八、验证
- 启动 Elasticsearch 9.0.0(默认端口 9200)。
- 启动 Spring Boot,首次访问任意接口时,Spring Data 会自动根据
@Document
注解创建index_popyu
并写入你给出的
mapping(已内置)。 - 使用 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);
总结
客户端 | 协议 | 状态 | 适用场景 |
---|---|---|---|
TransportClient | TCP | 已废弃 | 无 |
JestClient | HTTP | 非官方维护 | 轻量级需求(不推荐) |
RestClient | HTTP | 官方推荐 | 所有新版本(7.x/8.x) |
建议:
- 7.x:使用
RestHighLevelClient
(已废弃但可用)。 - 8.x:迁移到
Java API Client
(基于 REST,官方支持)。