SpringBoot3整合 Elasticsearch 8.x 使用Repository構建增刪改查示例應用
上一篇文章介紹了 Spring Boot 3 整合 Elasticsearch 8.x 的幾種客戶端形式,除此之外,Spring Data 對 Elasticsearch 還提供了 Repository 支持,與前面討論的JPA Repository 一樣,其基本原理是根據(jù)方法名稱自動為你構建查詢,提供了更簡便的數(shù)據(jù)搜索和分析功能。本文將介紹如何使用 Spring Data Elasticsearch Repository 來構建一個簡單的搜索應用。
1. 環(huán)境準備
1.1 項目依賴
在 pom.xml 中添加以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>確保 spring-boot-starter-data-elasticsearch 的版本與 Spring Boot 3 兼容。
1.2 Elasticsearch 配置
在 application.properties 或 application.yml 中配置 Elasticsearch 的連接信息:
spring:
elasticsearch:
uris: "http://localhost:9200"
socket-timeout: "10s"
username: "user"
password: "secret"2. 使用Repository的基本步驟
2.1 創(chuàng)建實體類
我們定義一個 Product 實體類,表示產(chǎn)品信息:
package com.coderjia.boot318es.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author CoderJia
* @create 2024/11/3 下午 04:37
* @Description
**/
@Data
@Document(indexName = "products")
@AllArgsConstructor
public class Product {
@Id
private String id;
private String name;
private String description;
private double price;
}2.2 創(chuàng)建 Repository 接口
ElasticsearchRepository 是 Spring Data Elasticsearch 提供的一個接口,用于簡化與 Elasticsearch 交互的操作。它繼承自 CrudRepository 和 PagingAndSortingRepository,擴展了基本的 CRUD(創(chuàng)建、讀取、更新、刪除)功能,支持分頁和排序,還提供了對 Elasticsearch 特有的操作支持。使用 ElasticsearchRepository,開發(fā)者可以快速構建功能全面的數(shù)據(jù)訪問層,而無需編寫復雜的 Elasticsearch 客戶端代碼。
2.2.1 主要作用和優(yōu)點
- 簡化數(shù)據(jù)操作:提供了基礎的 CRUD 方法,如
save()、findById()、findAll()和deleteById()等,方便開發(fā)者直接使用。 - 自定義查詢:通過定義接口中的方法(如
findByName(String name)),可以自動生成符合方法命名規(guī)范的查詢。 - 分頁與排序:內(nèi)置了分頁和排序支持,方法如
findAll(Pageable pageable)可以直接返回分頁數(shù)據(jù)。 - 與 Spring 無縫集成:使用 Spring 的依賴注入和配置機制,無需手動創(chuàng)建或管理客戶端連接。
- 減少代碼復雜度:自動實現(xiàn)常用的數(shù)據(jù)庫操作,減少重復代碼,提高開發(fā)效率。
2.2.2 使用場景
- 需要快速實現(xiàn)基于 Elasticsearch 的應用程序,且不希望編寫底層客戶端調(diào)用代碼。
- 開發(fā)中涉及到簡單或中等復雜度的查詢,使用方法命名約定生成查詢即可滿足需求。
- 項目中需要分頁、排序功能而不想手動處理分頁邏輯。
定義 ProductRepository 接口,繼承 ElasticsearchRepository:
package com.coderjia.boot318es.dao;
import com.coderjia.boot318es.bean.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
/**
* @author CoderJia
* @create 2024/11/4 下午 09:29
* @Description
**/
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
/**
* 自定義通過name查詢
*
* @param name
* @return
*/
List<Product> findByName(String name);
}2.3 服務層實現(xiàn)
在服務層中實現(xiàn)增刪改查的業(yè)務邏輯:
package com.coderjia.boot318es.service;
import com.coderjia.boot318es.bean.Product;
import com.coderjia.boot318es.dao.ProductRepository;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
/**
* @author CoderJia
* @create 2024/11/4 下午 09:29
* @Description
**/
@Service
public class ProductService {
@Resource
private ProductRepository productRepository;
// 創(chuàng)建或更新產(chǎn)品
public Product saveProduct(Product product) {
return productRepository.save(product);
}
// 根據(jù) ID 查詢產(chǎn)品
public Optional<Product> findById(String id) {
return productRepository.findById(id);
}
// 根據(jù)名稱查詢產(chǎn)品
public List<Product> findByName(String name) {
return productRepository.findByName(name);
}
// 獲取所有產(chǎn)品
public Page<Product> findAll(Pageable pageable) {
return productRepository.findAll(pageable);
}
// 刪除產(chǎn)品
public void deleteProduct(String id) {
productRepository.deleteById(id);
}
}2.4 控制器層
在控制器層實現(xiàn) REST API 接口,處理增刪改查請求:
package com.coderjia.boot318es.controller;
import com.coderjia.boot318es.bean.Product;
import com.coderjia.boot318es.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
/**
* @author CoderJia
* @create 2024/11/4 下午 09:30
* @Description
**/
@RestController
@RequestMapping("/products")
public class ProductController {
@Resource
private ProductService productService;
// 創(chuàng)建或更新產(chǎn)品
@PostMapping
public Product createOrUpdateProduct(@RequestBody Product product) {
return productService.saveProduct(product);
}
// 根據(jù) ID 查詢產(chǎn)品
@GetMapping("/{id}")
public Optional<Product> getProductById(@PathVariable String id) {
return productService.findById(id);
}
// 根據(jù)名稱查詢產(chǎn)品
@GetMapping("/search")
public List<Product> searchByName(@RequestParam String name) {
return productService.findByName(name);
}
// 獲取所有產(chǎn)品
@GetMapping
public List<Product> getAllProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Pageable pageable = PageRequest.of(page, size);
Page<Product> products = productService.findAll(pageable);
return products.getContent();
}
// 刪除產(chǎn)品
@DeleteMapping("/{id}")
public String deleteProduct(@PathVariable String id) {
productService.deleteProduct(id);
return "Product deleted successfully!";
}
}3. 測試應用
3.1 啟動 Elasticsearch
確保 Elasticsearch 8.x 正在運行,并且可以通過 http://localhost:9200 訪問。
3.2 啟動 Spring Boot 應用
運行 Spring Boot 應用,確保沒有錯誤。
3.3 測試 API
創(chuàng)建產(chǎn)品:
POST http://localhost:8080/products
Content-Type: application/json
{
"id": "1",
"name": "coderjia",
"description": "desc v1",
"price": 1.0
}
更新產(chǎn)品:
POST http://localhost:8080/products
Content-Type: application/json
{
"id": "1",
"name": "coderjia",
"description": "desc v2",
"price": 2.0
}
根據(jù) ID 查詢產(chǎn)品:
GET http://localhost:8080/products/1

根據(jù)名稱查詢產(chǎn)品:
GET http://localhost:8080/products/search?name=coderjia

獲取所有產(chǎn)品(分頁):
GET http://localhost:8080/products?page=0&size=3

刪除產(chǎn)品:
DELETE http://localhost:8080/products/1

4. 總結
通過以上步驟,我們構建了一個完整的 Spring Boot 3 和 Elasticsearch 8.x 的增刪改查示例應用。使用 Spring Data Elasticsearch Repository,我們能夠快速實現(xiàn)對 Elasticsearch 的基本 CRUD 操作,簡化了開發(fā)流程。希望這個示例能夠幫助你理解如何在項目中有效使用 Elasticsearch!
到此這篇關于SpringBoot3整合 Elasticsearch 8.x 使用Repository構建增刪改查示例應用的文章就介紹到這了,更多相關SpringBoot3整合 Elasticsearch 8.x內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Cloud學習教程之Zuul統(tǒng)一異常處理與回退
Spring Cloud Zuul對異常的處理整體來說還是比較方便的,流程也比較清晰,下面這篇文章主要給大家介紹了關于Spring Cloud學習教程之Zuul統(tǒng)一異常處理與回退的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧。2018-04-04
詳解springMVC之與json數(shù)據(jù)交互方法
本篇文章主要介紹了詳解springMVC之與json數(shù)據(jù)交互方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
解決springboot 2.x集成log4j2調(diào)試日志無法關閉的問題
這篇文章主要介紹了解決springboot 2.x集成log4j2調(diào)試日志無法關閉的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

