SpringBoot集成elasticsearch使用(增删改查)_spring boot es
在Spring Boot中集成Elasticsearch,可以使用Spring Data Elasticsearch。以下是一个简单的例子展示如何进行增删改查操作:
- 添加依赖到
pom.xml
:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>
- 配置
application.properties
或application.yml
:
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
- 创建一个实体类:
@Document(indexName = "sampleindex")
public class SampleEntity {
@Id
private String id;
private String content;
// 省略getter和setter
}
- 创建一个Elasticsearch仓库接口:
public interface SampleEntityRepository extends ElasticsearchRepository<SampleEntity, String> {
}
- 使用仓库进行操作:
@Service
public class SampleService {
@Autowired
private SampleEntityRepository repository;
public SampleEntity addEntity(SampleEntity entity) {
return repository.save(entity);
}
public Iterable<SampleEntity> getAllEntities() {
return repository.findAll();
}
public Optional<SampleEntity> getEntityById(String id) {
return repository.findById(id);
}
public SampleEntity updateEntity(String id, String content) {
SampleEntity entity = new SampleEntity();
entity.setId(id);
entity.setContent(content);
return repository.save(entity);
}
public void deleteEntityById(String id) {
repository.deleteById(id);
}
}
以上代码展示了如何在Spring Boot应用中集成Elasticsearch,并使用Spring Data Elasticsearch进行基本的增删改查操作。记得根据实际情况调整配置和实体类属性。
评论已关闭