在Elasticsearch 7.3中结合Spring Boot进行增删改查和批量操作,可以利用spring-data-elasticsearch
库简化开发过程。以下是一个简化的实战指南:
配置Spring Boot与Elasticsearch连接
首先,在Spring Boot项目中添加相应的Maven或Gradle依赖:
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.4.x</version> <!-- 根据你的Spring Boot版本选择合适的依赖版本 -->
</dependency>
<!-- Gradle -->
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch:2.4.x'
}
配置文件 application.yml 或 application.properties 中配置Elasticsearch服务器地址:
# application.yml
spring:
data:
elasticsearch:
cluster-name: your-cluster-name
cluster-nodes: localhost:9200
定义实体类
创建一个代表Elasticsearch文档的Java实体类,并使用@Document
注解标注:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "book-index")
public class Book {
@Id
private String id;
private String title;
private String author;
// ... 其他属性,构造函数,getter/setter
}
创建Repository接口
创建一个继承自ElasticsearchRepository
的repository接口,以便进行CRUD操作:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BookRepository extends ElasticsearchRepository<Book, String> {
// 可以定义自定义的查询方法
List<Book> findByAuthor(String author);
// 批量保存
Iterable<Book> saveAll(Iterable<Book> books);
}
使用Repository进行操作
在服务层或控制器中使用Repository进行增删改查:
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public void createBook(Book book) {
bookRepository.save(book);
}
public void updateBook(Book updatedBook) {
bookRepository.save(updatedBook); // ID相同的情况下会自动更新
}
public void deleteBookById(String id) {
bookRepository.deleteById(id);
}
public List<Book> findAllBooks() {
return bookRepository.findAll();
}
// 批量操作示例
public void bulkSave(List<Book> books) {
bookRepository.saveAll(books);
}
}
批量(Bulk)操作
对于复杂的批量操作,可以直接使用ElasticsearchRestTemplate
或者BulkProcessor
类:
@Autowired
private ElasticsearchRestHighLevelClient client;
public void bulkIndex(List<Book> books) throws IOException {
BulkRequest request = new BulkRequest();
for (Book book : books) {
IndexRequest indexRequest = new IndexRequest("book-index");
indexRequest.id(book.getId());
indexRequest.source(objectMapper.writeValueAsString(book));
request.add(indexRequest);
}
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
// 检查响应以确认是否有任何错误
}
以上代码片段展示了如何在Spring Boot应用中与Elasticsearch进行交互,包括基本的增删改查以及批量索引的操作。请根据实际情况调整配置和代码细节。