常用方法
- next()
从结果集中获取下一个
Result
对象。如果没有更多数据,则返回 null
。
示例:
ResultScanner scanner = table.getScanner(new Scan());
Result result = scanner.next();
while (result != null) {
// 处理 result
result = scanner.next();
}
scanner.close();
- next(int nbRows)
从结果集中获取指定数量的
Result
对象。返回的是一个 Result
数组。
示例:
ResultScanner scanner = table.getScanner(new Scan());
Result[] results = scanner.next(10);
for (Result result : results) {
// 处理 result
}
scanner.close();
- close()
关闭
ResultScanner
,释放相关资源。必须在使用完 ResultScanner
后调用此方法,以避免资源泄漏。
示例:
ResultScanner scanner = table.getScanner(new Scan());
try {
// 获取和处理数据
Result result = scanner.next();
while (result != null) {
// 处理 result
result = scanner.next();
}
} finally {
scanner.close();
}
业务场景
- 全表扫描场景:当需要获取表中的所有数据时,可使用
ResultScanner
进行全表扫描。例如,在数据统计场景中,统计某个 HBase 表中特定列族下所有数据的总和,就需要遍历全表获取所有相关数据。
Scan scan = new Scan();
ResultScanner scanner = table.getScanner(scan);
long sum = 0;
Result result = scanner.next();
while (result != null) {
byte[] value = result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("col"));
if (value != null) {
sum += Long.parseLong(Bytes.toString(value));
}
result = scanner.next();
}
scanner.close();
System.out.println("Sum: " + sum);
- 范围查询场景:在按行键范围查询数据时,
ResultScanner
也很有用。比如,在时间序列数据存储中,按时间范围(时间戳作为行键一部分)查询特定时间段内的数据。
Scan scan = new Scan(Bytes.toBytes("20230101"), Bytes.toBytes("20230201"));
ResultScanner scanner = table.getScanner(scan);
Result result = scanner.next();
while (result != null) {
// 处理特定时间段内的数据
result = scanner.next();
}
scanner.close();