springboot es存储数据示例
时间: 2023-06-13 22:05:42 浏览: 52
下面是使用Spring Boot和Elasticsearch存储数据的示例:
1. 添加Elasticsearch依赖
在 `pom.xml` 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置Elasticsearch
在 `application.properties` 文件中添加以下配置:
```properties
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
```
3. 创建数据模型
创建一个Java类作为数据模型,并使用 `@Document` 注解指定其在Elasticsearch中的索引和类型。
```java
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "article", type = "content")
public class Article {
@Id
private String id;
private String title;
private String content;
// 省略getter和setter方法
}
```
4. 创建Elasticsearch操作接口
创建一个接口,继承 `ElasticsearchRepository` 接口,并指定其操作的数据模型类型。
```java
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ArticleRepository extends ElasticsearchRepository<Article, String> {
}
```
5. 使用Elasticsearch存储数据
在代码中使用 `ArticleRepository` 接口的方法来存储数据。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ArticleService {
@Autowired
private ArticleRepository articleRepository;
public void save(Article article) {
articleRepository.save(article);
}
}
```
通过以上步骤,就可以使用Spring Boot和Elasticsearch来存储数据了。