HBase实现分页倒序查询

HBase的Scan查询功能(setStartRow, setStopRow),通过这两个方法,可以实现小范围的扫描,扫描的规则是[startRowKey,endRowKey),扫描的结果是起始行包括在内,终止行不包括在内。但rowkey的存储顺序是按照rowkey的ASCAII值排序,正常情况下是将ASCAII码值小的先查出来。要实现倒序查询,需要将startRow设置为终止行,endRow设置为起始行 ,然后设置scan.setReversed(true)即可实现倒序查询;

        ResultScanner scanner;
        Scan scan = new Scan();

        scan.addFamily(Bytes.toBytes(familyName));
        //过滤掉msgRecType=3的行     
        SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("c"),     
                 Bytes.toBytes("msgRecType"), CompareFilter.CompareOp.NOT_EQUAL, new 
                     SubstringComparator("3"));
        filter.setFilterIfMissing(true);
        Filter skipFilter = new SkipFilter(filter);
        scan.setFilter(skipFilter);
         if(order == 0){    //升序查询
             scan.setStartRow(Bytes.toBytes(startKey));
             scan.setStopRow(Bytes.toBytes(endKey));
         }
        if(order == 1){   //倒序查询
             scan.setStartRow(Bytes.toBytes(endKey));
             scan.setStopRow(Bytes.toBytes(startKey));
             scan.setReversed(true);   //HBase自带的方法,但需要将startRow设置为终止行,endRow设置为起始行 
                                                                   
        }
        Integer firstIndex = (currentPage - 1) * pageSize;  //当前查询页起始index
        try {
            scanner = table.getScanner(scan);
            if (firstIndex > 0) {
                scanner.next(firstIndex);
            }
            Result[] results = scanner.next(pageSize);
            Long total = findCount(tableName,familyName,startKey,endKey);   //total为查询总条数
            for (Result result : results) {
                List cellList = result.listCells();
                Map resultMap = new HashMap<>();
                for (Cell cell : cellList) {
                    resultMap.put(Bytes.toStringBinary(CellUtil.cloneQualifier(cell)), new String(CellUtil.cloneValue(cell),"UTF-8"));
                }
                resultList.add(resultMap);
            }

 

你可能感兴趣的:(HBase)