Spring Data Elasticsearch
ElasticsearchRepository、@Document。
40 分钟
Spring Data Elasticsearch
Spring Data Elasticsearch 提供 @Document、ElasticsearchRepository 与 ElasticsearchOperations,用法接近 JPA。适合在 spring-boot-essentials 项目中 附加 搜索能力,不替换 MySQL 主库。
学习目标
- 添加依赖并配置
spring.elasticsearch.uris - 定义
@Document实体与 Repository - 实现实验性搜索 API,与
TrackController分离
核心内容
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
Boot 3.x 默认 Elasticsearch Java API Client;版本需与 ES 8 服务端兼容。
配置
spring:
elasticsearch:
uris: http://localhost:9200
datasource:
url: jdbc:mysql://localhost:3306/codeforge # 保持不变
切勿 用 ES 替换 spring.datasource;与 mongodb-essentials 双数据源策略相同。
实体与 Repository
@Document(indexName = "tracks")
@Data
public class TrackDocument {
@Id
private String slug;
@Field(type = FieldType.Text, analyzer = "standard")
private String title;
@Field(type = FieldType.Text)
private String summary;
@Field(type = FieldType.Keyword)
private String category;
@Field(type = FieldType.Integer)
private Integer lessonCount;
}
public interface TrackSearchRepository
extends ElasticsearchRepository<TrackDocument, String> {
List<TrackDocument> findByCategory(String category);
}
复杂 DSL 注入 ElasticsearchOperations 构建 multi_match。实验端点 GET /api/lab/search/tracks?q= 读 ES;生产 GET /tracks 仍 JPA + MySQL。Track 与 TrackDocument 不共享 @Entity,变更 cf_track 后异步更新 ES(es-sync)。
练习
- 创建
TrackDocument+ Repository,启动连接 localhost:9200