prader6

es 分页查询




public<T> Page pageQuery(String index, ProgrammeRequest request, QueryBuilder queryBuilder,Class<T> tClass) throws IOException { Integer pageNum = request.getPageNum(); Integer pageSize = request.getPageSize(); int from = (pageNum - 1) * pageSize; SearchRequest searchRequest = new SearchRequest(index); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(queryBuilder) .from(from) .size(pageSize) .sort("id", SortOrder.ASC); searchRequest.source(builder); long total = 0; SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); if (searchResponse.status().equals(RestStatus.OK)){ long totalHits = searchResponse.getHits().getTotalHits().value; if (totalHits >= 10000){ // 去es 查询记录总数 CountRequest countRequest = new CountRequest(index); countRequest.source(builder); CountResponse count = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT); total = count.getCount(); }else { total = totalHits; } SearchHit[] hits = searchResponse.getHits().getHits(); List<T> records = Arrays.stream(hits).map(v -> JSONObject.parseObject(v.getSourceAsString(), tClass)).collect(Collectors.toList()); Page<T> tPage = new Page<>(); tPage.setRecords(records); tPage.setTotal(total); tPage.setSize(pageSize); tPage.setCurrent(pageNum); tPage.setPages(total / pageNum == 0 ? total / pageNum : total / pageNum + 1); return tPage; } return null; }

 做一下笔记

posted on 2023-05-10 17:10  prader6  阅读(115)  评论(0编辑  收藏  举报

导航