How to Get Latest Record in HBase

In HBase, the latest record can be queried by using the Scan class and ReverseScanFilter.

Here is an example code:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.filter.PrefixFilter;

import java.io.IOException;

public class HBaseLatestRecordQuery {
    public static void main(String[] args) throws IOException {
        // 创建配置对象
        Configuration conf = HBaseConfiguration.create();
        // 设置HBase的ZooKeeper地址
        conf.set("hbase.zookeeper.quorum", "localhost:2181");

        // 创建连接对象
        Connection connection = ConnectionFactory.createConnection(conf);
        // 创建表名对象
        TableName tableName = TableName.valueOf("your_table_name");
        // 创建表对象
        Table table = connection.getTable(tableName);

        // 创建Scan对象
        Scan scan = new Scan();
        // 设置过滤器为倒序扫描
        scan.setReversed(true);
        // 设置最大返回结果数为1
        scan.setMaxResultSize(1);

        // 添加过滤器,只返回第一行
        Filter filter = new FirstKeyOnlyFilter();
        scan.setFilter(filter);

        // 执行查询
        ResultScanner scanner = table.getScanner(scan);

        // 遍历结果
        for (Result result : scanner) {
            // 处理结果
            Cell cell = result.listCells().get(0);
            String rowKey = Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
            // 输出最新记录的行键
            System.out.println("Latest record: " + rowKey);
        }

        // 关闭资源
        scanner.close();
        table.close();
        connection.close();
    }
}

Please replace “your_table_name” in the code with the name of the table you want to query.

This code utilizes the Java API of HBase for querying. We start by creating a Scan object with reverse scanning and setting the maximum number of results to 1. Then, we add a filter to only return the first row. Finally, we iterate through the results and process the latest record.

With this, you can query the latest record in HBase by using the code above.

bannerAds