springboot做ES增删改查
时间: 2023-09-02 08:07:00 浏览: 156
使用 Spring Boot 操作 Elasticsearch 的增删改查可以通过 Elasticsearch 的 Java API 完成。以下是一个简单的示例:
1. 添加 Elasticsearch Maven 依赖
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.13.1</version>
</dependency>
```
2. 创建 Elasticsearch 客户端连接
```java
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http")
);
return new RestHighLevelClient(builder);
}
}
```
3. 定义 Elasticsearch 数据模型
```java
@Document(indexName = "my_index", createIndex = true)
public class Book {
@Id
private String id;
private String title;
private String author;
private String content;
// 省略 getter 和 setter 方法
}
```
4. 定义 Elasticsearch 数据访问层接口
```java
@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
}
```
5. 实现 Elasticsearch 数据访问层接口
```java
@Service
public class BookService {
private final BookRepository bookRepository;
public BookService(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
public void save(Book book) {
bookRepository.save(book);
}
public Book getById(String id) {
return bookRepository.findById(id).orElse(null);
}
public void deleteById(String id) {
bookRepository.deleteById(id);
}
public List<Book> search(String query) {
SearchHit[] searchHits = searchHits(query);
List<Book> books = new ArrayList<>();
for (SearchHit searchHit : searchHits) {
books.add(searchHit.getSourceAsMap());
}
return books;
}
private SearchHit[] searchHits(String query) {
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryStringQuery(query));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
return searchResponse.getHits().getHits();
}
}
```
使用以上方法,你可以在 Spring Boot 中非常容易地操作 Elasticsearch,进行增删改查的操作。需要注意的是,Elasticsearch 的 Java API 非常强大,可以满足各种复杂的需求。如果你需要更多的细节,请查看 Elasticsearch 官方文档。
阅读全文