springboot整合elasticsearch代码
时间: 2023-09-17 10:09:13 浏览: 98
以下是一个简单的Spring Boot应用程序,演示如何将Elasticsearch与Spring Boot集成:
1. 添加Elasticsearch依赖项:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置Elasticsearch连接:
```yaml
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: localhost:9300
```
3. 创建一个Elasticsearch实体:
```java
@Document(indexName = "myindex", type = "mytype")
public class MyEntity {
@Id
private String id;
private String name;
// getters and setters
}
```
4. 创建一个Elasticsearch存储库:
```java
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> {
List<MyEntity> findByName(String name);
}
```
5. 在应用程序中使用存储库:
```java
@Service
public class MyService {
@Autowired
private MyEntityRepository repository;
public void save(MyEntity entity) {
repository.save(entity);
}
public List<MyEntity> findByName(String name) {
return repository.findByName(name);
}
}
```
6. 至此,你已经可以使用Elasticsearch存储和检索数据了。
注意:在使用Elasticsearch时,请确保Elasticsearch正在运行,并且索引和类型已经被创建。
阅读全文