文档简介:
使用Get读取数据
功能简介
要从表中读取一条数据,首先需要实例化该表对应的Table实例,然后创建一个Get对
象。也可以为Get对象设定参数值,如列族的名称和列的名称。查询到的行数据存储在
Result对象中,Result中可以存储多个Cell。
代码样例
以下代码片段在cn.chinatelecom.hbase.sample包的“HBaseSample”类的sampleGet方
法中。
public static List<String> sampleGet(Connection conn) {
List<String> list = new ArrayList<>();
TableName tableName = TableName.valueOf("hbase-sample");
byte[] familyName = Bytes.toBytes("user");
byte[][] qualifier = {Bytes.toBytes("name"), Bytes.toBytes("age")};
byte[] rowKey = Bytes.toBytes("001");
Get get = new Get(rowKey);
get.addColumn(familyName, qualifier[0]);
get.addColumn(familyName, qualifier[1]);
try (Table table = conn.getTable(tableName)) {
Result result = table.get(get);
showData(list, result);
log.info("Get data successfully.");
} catch (IOException e) {
log.error("Get 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);
}
}