springboot集成es
时间: 2023-09-09 17:09:48 浏览: 103
要在 Spring Boot 中集成 Elasticsearch,需要两个主要依赖项:
1. `spring-boot-starter-data-elasticsearch`:包含 Elasticsearch 的 Spring Data 实现,提供操作 Elasticsearch 的接口。
2. `elasticsearch`:Java 客户端,用于与 Elasticsearch 进行交互。
以下是一个简单的 Spring Boot 集成 Elasticsearch 的示例:
1. 添加依赖项:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.9.3</version>
</dependency>
</dependencies>
```
2. 配置 Elasticsearch:
```properties
spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=localhost:9300
```
3. 创建实体类:
```java
@Document(indexName = "book")
public class Book {
@Id
private String id;
private String title;
private String author;
// getters and setters
}
```
4. 创建 Elasticsearch 仓库:
```java
@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
List<Book> findByTitle(String title);
}
```
5. 编写测试用例:
```java
@SpringBootTest
class BookRepositoryTest {
@Autowired
private BookRepository bookRepository;
@Test
void testSave() {
Book book = new Book();
book.setId("1");
book.setTitle("Java Programming");
book.setAuthor("John Doe");
bookRepository.save(book);
}
@Test
void testFindByTitle() {
List<Book> books = bookRepository.findByTitle("Java Programming");
// assert books size
}
}
```
以上示例演示了如何使用 Spring Boot 集成 Elasticsearch,并创建一个简单的 Elasticsearch 仓库来保存和查询 Book 实体。
阅读全文