返回
HBase 不睡觉:第四章 客户端 API 入门指南
见解分享
2023-11-10 06:47:10
本指南作为 HBase 客户端 API 的入门教程,将深入讲解如何使用 HBase 客户端 API 开发各种应用程序。
在本章中,我们将学习如何连接到 HBase 集群,如何创建和管理表,如何插入和读取数据,以及如何执行查询。我们还将学习一些高级主题,如事务和过滤器。
连接到 HBase 集群
Configuration config = HBaseConfiguration.create();
Connection connection = ConnectionFactory.createConnection(config);
创建和管理表
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("my_table"));
HColumnDescriptor columnDescriptor = new HColumnDescriptor("my_column_family");
tableDescriptor.addFamily(columnDescriptor);
Admin admin = connection.getAdmin();
admin.createTable(tableDescriptor);
插入和读取数据
Put put = new Put(Bytes.toBytes("row_key"));
put.addColumn(Bytes.toBytes("my_column_family"), Bytes.toBytes("my_column"), Bytes.toBytes("my_value"));
Table table = connection.getTable(TableName.valueOf("my_table"));
table.put(put);
Get get = new Get(Bytes.toBytes("row_key"));
Result result = table.get(get);
byte[] value = result.getValue(Bytes.toBytes("my_column_family"), Bytes.toBytes("my_column"));
执行查询
Scan scan = new Scan();
Table table = connection.getTable(TableName.valueOf("my_table"));
ResultScanner results = table.getScanner(scan);
for (Result result : results) {
byte[] rowKey = result.getRow();
byte[] value = result.getValue(Bytes.toBytes("my_column_family"), Bytes.toBytes("my_column"));
}
高级主题
事务
TransactionOptions options = TransactionOptions.newBuilder().setDurability(Durability.ASYNC_WAL).build();
try (Transaction tx = connection.beginTransaction(options)) {
Get get = new Get(Bytes.toBytes("row_key"));
Result result = table.get(get);
byte[] value = result.getValue(Bytes.toBytes("my_column_family"), Bytes.toBytes("my_column"));
Put put = new Put(Bytes.toBytes("row_key"));
put.addColumn(Bytes.toBytes("my_column_family"), Bytes.toBytes("my_column"), Bytes.toBytes(value));
table.put(put);
tx.commit();
} catch (Exception e) {
tx.rollback();
}
过滤器
Filter filter = new RowFilter(CompareFilter.CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("my_value")));
Scan scan = new Scan().setFilter(filter);
Table table = connection.getTable(TableName.valueOf("my_table"));
ResultScanner results = table.getScanner(scan);
for (Result result : results) {
byte[] rowKey = result.getRow();
byte[] value = result.getValue(Bytes.toBytes("my_column_family"), Bytes.toBytes("my_column"));
}