ElasticSearch:分页查询(jest操作)

两种做法:深度分页和浅分页

  • 分页类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Page<T> {
    private int pageSize = 10; //每页显示条数
    private int totalCount; //总条数
    private int start; //开始条数
    private int pageNo;//当前页
    private int totalPages; //总页数
    private List<T> pageList;//数据

    public Page(int totalCount) {
        this.totalCount = totalCount;
    }

    /**
     * 获取下一条
     */
    public int getCurrentPageNo() {
        return start / pageSize + 1;
    }

    /**
     * 是否有下一条
     *
     * @return
     */
    public boolean getHasNextPage() {
        return getCurrentPageNo() < totalPages;
    }

    /**
     * 当前页是否大于1
     *
     * @return
     */
    public boolean getHasPavPage() {
        return getCurrentPageNo() > 1;
    }

    /**
     * 获取总页数
     *
     * @return
     */
    public int getTotalPages() {
        totalPages = totalCount / pageSize;

        if (totalCount % pageSize != 0) {
            totalPages++;
        }

        return totalPages;
    }

    /**
     * 设置当前页的开始条数
     *
     * @param pageNo
     * @return
     */
    public int getStart(int pageNo) {
        if (pageNo < 1) {
            pageNo = 1;
        } else if (getTotalPages() > 0 && pageNo > getTotalPages()) {
            pageNo = getTotalPages();
        }

        start = (pageNo - 1) * pageSize;
        return start;
    }
}
  • dao
@Slf4j
@Repository
public class RecordDetailsDao extends JestBaseDao {


    /**
     * 交易记录列表信息查询
     *
     * @return
     */
    public SearchResult listRecordDetails(@NotBlank String esJson,
                                          @NotBlank String serviceName) {
        if (StringUtils.contains(serviceName, "_")) {
            int index = StringUtils.indexOf(serviceName, "_");
            String indexName = StringUtils.substring(serviceName, 0, index);
            String indexAllName = indexName.concat("*");
            return this.queryResByJsonStr(esJson, indexAllName, JestConsts.Index.AUTHS.getIndexType());
        }
        return null;
    }
}
  • service
@Slf4j
@Service
public class RecordDetailsServiceImpl implements RecordDetailsService {

    private final RecordDetailsDao recordDetailsDao;

    @Autowired
    public RecordDetailsServiceImpl(RecordDetailsDao recordDetailsDao) {
        this.recordDetailsDao = recordDetailsDao;
    }


    @Override
    public Page<AllCentre> listRecordDetails(RecordDetails recordDetails) {

        SearchResult searchResult = this.searchResult(recordDetails);
        if (Objects.equals(searchResult, null)) {
            return new Page<AllCentre>().setPageList(Collections.emptyList());
        }
        //取es数据
        List<AllCentre> allCentreList = searchResult.getSourceAsObjectList(AllCentre.class, true);
        //总数
        Long valueCount = searchResult.getAggregations().getValueCountAggregation(JestConsts.AggName.SERVICE_NAME_COUNT).getValueCount();
        //分页
        return new Page<AllCentre>(valueCount.intValue()).setPageList(allCentreList);
    }

    @Override
    public List<SubCode> listSubCode(RecordDetails recordDetails) {
        SearchSourceBuilder source = SearchSourceBuilder.searchSource();
        BoolQueryBuilder bool = this.getBoolQuery(recordDetails);
        TermsAggregationBuilder termsAggs = AggregationBuilders.terms(JestConsts.AggName.SUB_CODE_GROUP).field(JestConsts.Keywords.SUB_CODE).size(100);
        String esJson = source.size(0).query(bool).aggregation(termsAggs).toString();
        log.info("{}", esJson);
        SearchResult searchResult = recordDetailsDao.listRecordDetails(esJson, recordDetails.getTacheCode());
        if (Objects.equals(searchResult, null)) {
            return Collections.emptyList();
        }
        List<TermsAggregation.Entry> entryList = searchResult.getAggregations().getTermsAggregation(JestConsts.AggName.SUB_CODE_GROUP).getBuckets();
        return entryList.stream().map(entry -> SubCode.builder().statusCode(entry.getKeyAsString()).statusName(entry.getKeyAsString()).build()).collect(Collectors.toList());
    }

    /**
     * 查询jest返回SearchResult
     *
     * @param recordDetails
     * @return
     */
    @NotNull
    private SearchResult searchResult(RecordDetails recordDetails) {
        SearchSourceBuilder source = SearchSourceBuilder.searchSource();
        BoolQueryBuilder bool = this.getBoolQuery(recordDetails);
        if (StringUtils.isNotBlank(recordDetails.getSubCode())) {
            bool.filter(QueryBuilders.termQuery(JestConsts.Keywords.SUB_CODE, recordDetails.getSubCode()));
        }
        ValueCountAggregationBuilder count = AggregationBuilders
                .count(JestConsts.AggName.SERVICE_NAME_COUNT)
                .field(JestConsts.Keywords.SERVICE_NAME);
        String esJson = source.from(recordDetails.getStart()).size(recordDetails.getLength()).query(bool).aggregation(count).toString();
        log.info("{}", esJson);
        return recordDetailsDao.listRecordDetails(esJson, recordDetails.getTacheCode());
    }

    /**
     * @param recordDetails
     * @return
     */
    private BoolQueryBuilder getBoolQuery(RecordDetails recordDetails) {
        Long beginTime = LocalDateTimeUtils.getTimeStampByDateTime(recordDetails.getBeginTime());
        Long endTime = LocalDateTimeUtils.getTimeStampByDateTime(recordDetails.getEndTime());
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        bool.filter(QueryBuilders.rangeQuery(JestConsts.Keywords.LOG_TIME_LONG)
                .gte(beginTime)
                .lte(endTime));
        bool.filter(QueryBuilders.termQuery(JestConsts.Keywords.SERVICE_NAME, recordDetails.getTacheCode()));
        bool.filter(QueryBuilders.termQuery(JestConsts.Keywords.MSG_IS_JSON, 1));
        bool.mustNot(QueryBuilders.termQuery(JestConsts.Keywords.SUB_CODE, "0000"));
        return bool;
    }

}
  • controller
    @PostMapping(value = "/recordData", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询动态表格信息")
    public AbstractApiResult listRecordDetails(@Validated RecordDetails recordDetails) {
        Page<AllCentre> objectPage = recordDetailsService.listRecordDetails(recordDetails);
        return AbstractApiResult.success(objectPage);
    }

你可能感兴趣的:(Elasticsearch,SpringBoot学习总结)