Elasticsearch8.x Spring Data and Spring Boot 3 尝鲜
问题描述不是很清晰,但我猜你可能想要知道如何在Spring Boot 3和Spring Data中集成Elasticsearch 8.x版本。
以下是一个基本的示例,展示了如何在Spring Boot 3项目中配置和使用Spring Data Elasticsearch 8.x。
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Boot 3 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data Elasticsearch 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 在
application.properties
或application.yml
中配置Elasticsearch属性:
spring.data.elasticsearch.cluster-name=my-elasticsearch-cluster
spring.data.elasticsearch.cluster-nodes=localhost:9300
- 创建一个实体类来表示你的文档:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "my_index")
public class MyEntity {
@Id
private String id;
private String data;
// Getters and Setters
}
- 创建一个Repository接口:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> {
// 自定义查询方法
}
- 使用Repository进行操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class MyEntityService {
@Autowired
private MyEntityRepository repository;
public MyEntity create(MyEntity entity) {
return repository.save(entity);
}
public Optional<MyEntity> findById(String id) {
return repository.findById(id);
}
}
- 创建一个测试类来验证Elasticsearch的功能:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@Sp
评论已关闭