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);}
}
八、驗證
- 啟動 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,官方支持)。