hbase timestamp 在查询中如何用

作者:袖梨 2026-08-03

在 HBase 查询中,您可以使用 TimestampFilter 来根据时间戳过滤数据

以下是如何在 HBase Shell 中使用 TimestampFilter 的示例:

# 进入 HBase Shellhbase shell# 选择要查询的表table_name = "your_table_name"# 设置查询的时间范围start_timestamp = 1609459200000 # 2021-01-01 00:00:00 UTCend_timestamp = 1611935999000 # 2021-02-01 00:00:00 UTC# 创建 TimestampFilter 对象timestamp_filter = org.apache.hadoop.hbase.filter.TimestampFilter.newBuilder().setMinTimestamp(start_timestamp).setMaxTimestamp(end_timestamp).build()# 使用 TimestampFilter 进行查询scan = org.apache.hadoop.hbase.client.Scan()scan.setFilter(timestamp_filter)result = table_name.getScanner(scan).next()# 处理查询结果while (result != null) {// 处理每一行数据row = result.getRow()print("Row key:", row)// ... 其他处理逻辑# 继续获取下一行结果result = table_name.getScanner(scan).next()}

如果您使用的是 HBase Java API,可以使用以下代码示例:

import org.apache.hadoop.hbase.*;import org.apache.hadoop.hbase.client.*;import org.apache.hadoop.hbase.filter.*;import java.io.IOException;publicclassHBaseTimestampFilterExample {publicstaticvoidmain(String[] args)throws IOException {// 创建 HBase 连接Configurationconf= HBaseConfiguration.create();Connectionconnection= ConnectionFactory.createConnection(conf);Adminadmin= connection.getAdmin();// 选择要查询的表TableNametable_name= TableName.valueOf("your_table_name");// 设置查询的时间范围longstart_timestamp=1609459200000L; // 2021-01-01 00:00:00 UTClongend_timestamp=1611935999000L; // 2021-02-01 00:00:00 UTC// 创建 TimestampFilter 对象TimestampFiltertimestamp_filter=newTimestampFilter(start_timestamp, end_timestamp);// 使用 TimestampFilter 进行查询Scanscan=newScan();scan.setFilter(timestamp_filter);ResultScannerresult_scanner= table_name.getScanner(scan);// 处理查询结果for (Result result : result_scanner) {// 处理每一行数据byte[] row_key = result.getRow();System.out.println("Row key:", Bytes.toString(row_key));// ... 其他处理逻辑}// 关闭资源result_scanner.close();admin.close();connection.close();}}

请注意,这些示例中的时间戳是以毫秒为单位的自 1970 年 1 月 1 日(UTC)以来的时间戳。您需要根据您的需求设置合适的时间范围。

相关文章

精彩推荐