Spring Data Elasticsearch 是 Spring 生态系统的一部分,提供了与 Elasticsearch 集成的便捷方式,允许开发者使用熟悉的 Spring Data 抽象和注解来操作 Elasticsearch。以下是一个使用 Spring Data Elasticsearch 的实战指南:
1. 添加依赖
在 Maven 或 Gradle 项目中添加 Spring Data Elasticsearch 依赖:
Maven:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
</dependencies>
Gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'
}
2. 配置 Elasticsearch 连接
在 application.properties
或 application.yml
中配置 Elasticsearch 服务器地址和端口:
spring.data.elasticsearch.cluster-name=my_cluster
spring.data.elasticsearch.cluster-nodes=localhost:9300
3. 定义实体类
创建一个代表 Elasticsearch 文档的 Java 类,并使用 Spring Data Elasticsearch 注解进行标注。例如,定义一个 Book
类:
@Document(indexName = "book", type = "_doc")
public class Book {
@Id
private String id;
@Field(type = FieldType.Text)
private String title;
@Field(type = FieldType.Keyword)
private String author;
@Field(type = FieldType.Date, format = DateFormat.date)
private LocalDate publicationDate;
// 构造函数、getter/setter、equals/hashCode/toString 等方法
}
4. 创建 Repository 接口
创建一个继承自 ElasticsearchRepository
的接口,用于执行 CRUD 操作。例如,创建 BookRepository
:
public interface BookRepository extends ElasticsearchRepository<Book, String> {
List<Book> findByAuthor(String author);
Page<Book> findByPublicationDateBetween(LocalDate startDate, LocalDate endDate, Pageable pageable);
}
5. 使用 Repository 进行操作
在 Service 或 Controller 中注入 BookRepository
并使用它执行查询、保存、删除等操作:
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public void saveBook(Book book) {
bookRepository.save(book);
}
public List<Book> findBooksByAuthor(String author) {
return bookRepository.findByAuthor(author);
}
public Page<Book> findBooksByPublicationDate(LocalDate startDate, LocalDate endDate, Pageable pageable) {
return bookRepository.findByPublicationDateBetween(startDate, endDate, pageable);
}
// 其他操作...
}
6. 自定义查询方法
如果需要执行更复杂的查询,可以使用 @Query
注解在 Repository 方法上定义原生 Elasticsearch 查询 DSL:
public interface BookRepository extends ElasticsearchRepository<Book, String> {
@Query("{\"bool\":{\"must\":[{\"match\":{\"title\":\"?0\"}},{\"match\":{\"author\":\"?1\"}}]}}")
List<Book> findByTitleAndAuthor(String title, String author);
}
7. 配置自定义 ElasticsearchTemplate
如果需要自定义 Elasticsearch 操作,如使用不同的映射配置、索引模板等,可以创建一个 ElasticsearchConfiguration
类并配置 ElasticsearchTemplate
:
@Configuration
public class ElasticsearchConfig {
@Autowired
private ElasticsearchProperties properties;
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client(), new CustomEntityMapper());
}
@Bean
public RestHighLevelClient client() {
return RestClients.create(properties.getUris()).rest();
}
}
8. 索引管理
使用 ElasticsearchOperations
或 IndexOperations
进行索引管理,如创建索引、添加映射、刷新索引等:
@Autowired
private ElasticsearchOperations operations;
public void setupIndex() {
IndexOperations indexOps = operations.indexOps(Book.class);
if (!indexOps.exists()) {
indexOps.create();
}
indexOps.putMapping(Book.class);
indexOps.refresh();
}
通过上述步骤,您已经成功将 Spring Data Elasticsearch 集成到您的 Spring Boot 应用中,并能够利用 Spring Data 的抽象和便利性来操作 Elasticsearch。根据实际需求,您可以进一步定制 Elasticsearch 配置、扩展 Repository 功能、实现复杂查询等。