springboot 集成es的查询api
时间: 2023-11-24 11:06:42 浏览: 101
Spring Boot集成ES的查询API可以通过以下步骤实现:
1. 添加Elasticsearch依赖
在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置Elasticsearch连接信息
在`application.yml`或`application.properties`文件中添加以下配置:
```yaml
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: localhost:9300
```
3. 创建Elasticsearch Repository
创建一个继承自`ElasticsearchRepository`的Repository接口,用于定义查询方法。
```java
public interface BookRepository extends ElasticsearchRepository<Book, Long> {
List<Book> findByTitle(String title);
List<Book> findByAuthor(String author);
List<Book> findByTitleAndAuthor(String title, String author);
}
```
4. 使用Elasticsearch Repository 进行查询
在Service或Controller中使用`BookRepository`进行查询操作。
```java
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> search(String title, String author) {
if (StringUtils.isEmpty(title) && StringUtils.isEmpty(author)) {
return Collections.emptyList();
}
if (StringUtils.isEmpty(title)) {
return bookRepository.findByAuthor(author);
}
if (StringUtils.isEmpty(author)) {
return bookRepository.findByTitle(title);
}
return bookRepository.findByTitleAndAuthor(title, author);
}
}
```
以上就是Spring Boot集成ES的查询API的步骤。
阅读全文
相关推荐

















