SpringBoot3整合 Elasticsearch 8.x 使用Repository構(gòu)建增刪改查示例應(yīng)用
上一篇文章介紹了 Spring Boot 3 整合 Elasticsearch 8.x 的幾種客戶端形式,除此之外,Spring Data 對(duì) Elasticsearch 還提供了 Repository 支持,與前面討論的JPA Repository 一樣,其基本原理是根據(jù)方法名稱自動(dòng)為你構(gòu)建查詢,提供了更簡(jiǎn)便的數(shù)據(jù)搜索和分析功能。本文將介紹如何使用 Spring Data Elasticsearch Repository 來(lái)構(gòu)建一個(gè)簡(jiǎn)單的搜索應(yīng)用。
1. 環(huán)境準(zhǔn)備
1.1 項(xiàng)目依賴
在 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)建實(shí)體類
我們定義一個(gè) Product
實(shí)體類,表示產(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 提供的一個(gè)接口,用于簡(jiǎn)化與 Elasticsearch 交互的操作。它繼承自 CrudRepository
和 PagingAndSortingRepository
,擴(kuò)展了基本的 CRUD(創(chuàng)建、讀取、更新、刪除)功能,支持分頁(yè)和排序,還提供了對(duì) Elasticsearch 特有的操作支持。使用 ElasticsearchRepository
,開(kāi)發(fā)者可以快速構(gòu)建功能全面的數(shù)據(jù)訪問(wèn)層,而無(wú)需編寫(xiě)復(fù)雜的 Elasticsearch 客戶端代碼。
2.2.1 主要作用和優(yōu)點(diǎn)
- 簡(jiǎn)化數(shù)據(jù)操作:提供了基礎(chǔ)的 CRUD 方法,如
save()
、findById()
、findAll()
和deleteById()
等,方便開(kāi)發(fā)者直接使用。 - 自定義查詢:通過(guò)定義接口中的方法(如
findByName(String name)
),可以自動(dòng)生成符合方法命名規(guī)范的查詢。 - 分頁(yè)與排序:內(nèi)置了分頁(yè)和排序支持,方法如
findAll(Pageable pageable)
可以直接返回分頁(yè)數(shù)據(jù)。 - 與 Spring 無(wú)縫集成:使用 Spring 的依賴注入和配置機(jī)制,無(wú)需手動(dòng)創(chuàng)建或管理客戶端連接。
- 減少代碼復(fù)雜度:自動(dòng)實(shí)現(xiàn)常用的數(shù)據(jù)庫(kù)操作,減少重復(fù)代碼,提高開(kāi)發(fā)效率。
2.2.2 使用場(chǎng)景
- 需要快速實(shí)現(xiàn)基于 Elasticsearch 的應(yīng)用程序,且不希望編寫(xiě)底層客戶端調(diào)用代碼。
- 開(kāi)發(fā)中涉及到簡(jiǎn)單或中等復(fù)雜度的查詢,使用方法命名約定生成查詢即可滿足需求。
- 項(xiàng)目中需要分頁(yè)、排序功能而不想手動(dòng)處理分頁(yè)邏輯。
定義 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> { /** * 自定義通過(guò)name查詢 * * @param name * @return */ List<Product> findByName(String name); }
2.3 服務(wù)層實(shí)現(xiàn)
在服務(wù)層中實(shí)現(xiàn)增刪改查的業(yè)務(wù)邏輯:
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 控制器層
在控制器層實(shí)現(xiàn) REST API 接口,處理增刪改查請(qǐng)求:
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. 測(cè)試應(yīng)用
3.1 啟動(dòng) Elasticsearch
確保 Elasticsearch 8.x 正在運(yùn)行,并且可以通過(guò) http://localhost:9200
訪問(wèn)。
3.2 啟動(dòng) Spring Boot 應(yīng)用
運(yùn)行 Spring Boot 應(yīng)用,確保沒(méi)有錯(cuò)誤。
3.3 測(cè)試 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)品(分頁(yè)):
GET http://localhost:8080/products?page=0&size=3
刪除產(chǎn)品:
DELETE http://localhost:8080/products/1
4. 總結(jié)
通過(guò)以上步驟,我們構(gòu)建了一個(gè)完整的 Spring Boot 3 和 Elasticsearch 8.x 的增刪改查示例應(yīng)用。使用 Spring Data Elasticsearch Repository,我們能夠快速實(shí)現(xiàn)對(duì) Elasticsearch 的基本 CRUD 操作,簡(jiǎn)化了開(kāi)發(fā)流程。希望這個(gè)示例能夠幫助你理解如何在項(xiàng)目中有效使用 Elasticsearch!
到此這篇關(guān)于SpringBoot3整合 Elasticsearch 8.x 使用Repository構(gòu)建增刪改查示例應(yīng)用的文章就介紹到這了,更多相關(guān)SpringBoot3整合 Elasticsearch 8.x內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 解決SpringBoot整合ElasticSearch遇到的連接問(wèn)題
- SpringBoot整合Elasticsearch游標(biāo)查詢的示例代碼(scroll)
- es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程詳解
- SpringBoot整合Spring Data Elasticsearch的過(guò)程詳解
- SpringBoot整合Elasticsearch7.2.0的實(shí)現(xiàn)方法
- SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作
- 解決springboot無(wú)法注入JpaRepository的問(wèn)題
相關(guān)文章
關(guān)于IDEA 2020使用 mybatis-log-plugin插件的問(wèn)題
這篇文章主要介紹了關(guān)于IDEA 2020使用 mybatis-log-plugin插件的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11關(guān)于Idea使用git時(shí)commit特別慢的問(wèn)題及解決方法
這篇文章主要介紹了關(guān)于Idea使用git時(shí)commit特別慢的問(wèn)題及解決方法,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10IDEA創(chuàng)建javaee項(xiàng)目依賴war exploded變紅失效的解決方案
在使用IntelliJ IDEA創(chuàng)建JavaEE項(xiàng)目時(shí),可能會(huì)遇到Tomcat部署的warexploded文件出現(xiàn)問(wèn)題,解決方法是首先刪除有問(wèn)題的warexploded依賴,然后根據(jù)圖示重新導(dǎo)入項(xiàng)目,此外,調(diào)整虛擬路徑有時(shí)也能有效解決問(wèn)題2024-09-09spring AOP代理執(zhí)行@EnableAspectJAutoProxy的exposeProxy屬性詳解
這篇文章主要為大家介紹了spring AOP代理執(zhí)行@EnableAspectJAutoProxy的exposeProxy屬性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09SpringCloud整合OpenFeign實(shí)現(xiàn)微服務(wù)間的通信
微服務(wù)之間的通信?式,通常有兩種: RPC 和 HTTP,在SpringCloud中, 默認(rèn)是使?HTTP來(lái)進(jìn)?微服務(wù)的通信, 最常?的實(shí)現(xiàn)形式有兩種:RestTemplate和OpenFeign,本文給大家介紹了SpringCloud整合OpenFeign實(shí)現(xiàn)微服務(wù)間的通信,需要的朋友可以參考下2024-06-06