springboot集成elasticsearch分页查询
时间: 2025-05-31 12:08:01 浏览: 18
### 实现Spring Boot Elasticsearch分页查询
在Spring Boot应用程序中集成Elasticsearch并实现分页查询涉及多个方面。为了简化配置过程,Spring Boot会自动选择最近版本的Spring Data模块[^1]。
对于分页功能的支持,`Pageable`接口提供了必要的参数来定义分页行为。下面是一个简单的例子展示如何在一个控制器方法中利用`PagedResourcesAssembler`来进行分页处理:
```java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.hateoas.PagedModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
@RequestMapping("/elasticsearch")
public class ElasticSearchController {
private final ProductRepository productRepository; // 假设有一个Product实体类及其对应的仓库
@Autowired
public ElasticSearchController(ProductRepository productRepository) {
this.productRepository = productRepository;
}
/**
* 获取带有分页的产品列表.
*/
@GetMapping("/products")
public PagedModel<EntityModel<Product>> getProducts(
@RequestParam(value="page", defaultValue="0") int page,
@RequestParam(value="size", defaultValue="20") int size) {
PageRequest pageable = PageRequest.of(page, size);
Page<Product> productsPage = productRepository.findAll(pageable);
var assembler = new EntityModelAssembler<>(product -> Link.of("/elasticsearch/products/" + product.getId()));
return pagedResourcesAssembler.toModel(productsPage, assembler);
}
}
```
上述代码片段展示了如何通过RESTful API端点接收分页请求,并返回经过HATEOAS增强后的资源集合。这里使用了`EntityModelAssembler`来自定义链接生成逻辑;而`pagedResourcesAssembler.toModel()`则负责将`Page<T>`转换成适合客户端消费的形式[^4]。
此外,在实际应用开发过程中可能还需要考虑其他因素,比如性能优化、错误处理机制以及安全性等方面的内容。
阅读全文
相关推荐

















