文档简介:
使用Scan读取数据
功能简介
要从表中读取数据,首先需要实例化该表对应的Table实例,然后创建一个Scan对象,
并针对查询条件设置Scan对象的参数值,为了提高查询效率,最好指定StartRow和
StopRow。查询结果的多行数据保存在ResultScanner对象中,每行数据以Result对象形
式存储,Result中存储了多个Cell。
代码样例
以下代码片段在cn.chinatelecom.hbase.sample包的“HBaseSample”类的
sampleScan方法中。
public static List<String> sampleScan(Connection conn) {
List<String> list = new ArrayList<>();
TableName tableName = TableName.valueOf("hbase-sample");
Scan scan = new Scan();
scan.addColumn(Bytes.toBytes("user"), Bytes.toBytes("name"));
scan.setCaching(1000);
scan.withStartRow(Bytes.toBytes("001"));
// default not include stopRow
scan.withStopRow(Bytes.toBytes("003"));
try (Table table = conn.getTable(tableName); ResultScanner rScanner = table.getScanner(scan)) {
for (Result result : rScanner) {
showData(list, result);
}
log.info("Scan data successfully");
} catch (IOException e) {
log.error("Scan data failed ", e);
}
return list;
}
private static void showData(List<String> list, Result result) {
for (Cell cell : result.rawCells()) {
String temp = Bytes.toString(CellUtil.cloneRow(cell)) + ":"
+ Bytes.toString(CellUtil.cloneFamily(cell)) + ","
+ Bytes.toString(CellUtil.cloneQualifier(cell)) + ","
+ Bytes.toString(CellUtil.cloneValue(cell));
log.info(temp);
list.add(temp);
}
}
注意事项
1. 建议Scan时指定StartRow和StopRow,一个有确切范围的Scan,性能会更好些。
2. 可以设置Batch和Caching关键参数。
– Batch
使用Scan调用next接口每次最大返回的记录数,与一次读取的列数有关。
– Caching
RPC请求返回next记录的最大数量,该参数与一次RPC获取的行数有关。