更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞👍收藏⭐评论✍
整合 Elasticsearch 8.x (二)使用Repository
上一篇文章介绍了 Spring Boot 3 整合 Elasticsearch 8.x 的几种客户端形式,除此之外,Spring Data 对 Elasticsearch 还提供了 Repository 支持,与前面讨论的JPA Repository 一样,其基本原理是根据方法名称自动为你构建查询,提供了更简便的数据搜索和分析功能。本文将介绍如何使用 Spring Data Elasticsearch Repository 来构建一个简单的搜索应用。
1. 环境准备
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 创建实体类
我们定义一个 Product
实体类,表示产品信息:
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 创建 Repository 接口
ElasticsearchRepository
是 Spring Data Elasticsearch 提供的一个接口,用于简化与 Elasticsearch 交互的操作。它继承自 CrudRepository
和 PagingAndSortingRepository
,扩展了基本的 CRUD(创建、读取、更新、删除)功能,支持分页和排序,还提供了对 Elasticsearch 特有的操作支持。使用 ElasticsearchRepository
,开发者可以快速构建功能全面的数据访问层,而无需编写复杂的 Elasticsearch 客户端代码。
2.2.1 主要作用和优点
- 简化数据操作:提供了基础的 CRUD 方法,如
save()
、findById()
、findAll()
和deleteById()
等,方便开发者直接使用。 - 自定义查询:通过定义接口中的方法(如
findByName(String name)
),可以自动生成符合方法命名规范的查询。 - 分页与排序:内置了分页和排序支持,方法如
findAll(Pageable pageable)
可以直接返回分页数据。 - 与 Spring 无缝集成:使用 Spring 的依赖注入和配置机制,无需手动创建或管理客户端连接。
- 减少代码复杂度:自动实现常用的数据库操作,减少重复代码ÿ