使用 Java API 操作 HBase 数据库,就类似HBase Shell,本质上一个是Java 代码,一个是Shell 命令。(hadoop 的文件系统莫不如此,可用Java API 的方式操作hdfs,也可用shell 命令)。
在hbase 操作 一文我们介绍了使用命令行(HBase shell)的方式操作hbase,如果 Java 也可操作MySQL一样,本文我们着重介绍如何使用 Java API 操作 HBase。
hadoop hbase API 提供了两个核心的 API 用以操作hbase 数据库:
HBaseAdmin:
- 创建表:create
- 删除表:disable、drop
HTable:
- 插入记录:put
- 删除记录:delete、deleteall
- 遍历所有记录:scan
public class Test {
private static final String TABLE_NAME = "students";
private static final String FAMILY_1 = "stu_id";
private static final String FAMILY_2 = "addr";
private static final String FAMILY_3 = "info";
public static void main(String[] args) throws Exception {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.rootdir", "hdfs://hadoop0:hbase/");
conf.set("hbase.zookeeper.quorum", "hadoop0");
HBaseAdmin admin = new HBaseAdmin(conf);
if (!admin.tableExists(TABLE_NAME)){
HTableDescriptor desc = new HTableDescriptor(TABLE_NAME);
desc.addFamily(new HColumnDescriptor(FAMILY_1));
desc.addFamily(new HColumnDescriptor(FAMILY_2));
desc.addFamily(new HColumnDescriptor(FAMILY_3));
admin.createTable(desc);
// 等价于 hbase shell 中的:
// create 'students', 'stu_id', 'addr', 'info'
}
HTable table = new HTable(conf, TABLE_NAME);
Put put = new Put("xiaoming".getBytes());
put.add(FAMILY_3.getBytes(), "age".getBytes(), "24".getBytes());
// 一个 add 表示插入一个记录
// put 'students', 'xiaoming', 'info:age', "24"
put.add(FAMILY_3.getBytes(), "birthday".getBytes(), "1987-06-17".getBytes());
put.add(FAMILY_3.getBytes(), "company".getBytes(), "alibba".getBytes());
put.add(FAMILY_2.getBytes(), "contry".getBytes(), "china".getBytes());
put.add(FAMILY_2.getBytes(), "province".getBytes(), "zhejiang".getBytes());
put.add(FAMILY_2.getBytes(), "city".getBytes(), "hangzhou".getBytes());
table.put(put);
put = new Put("zhangyifei".getBytes());
put.add(FAMILY_3.getBytes(), "birthday".getBytes(), "1987-04-17".getBytes());
put.add(FAMILY_2.getBytes(), "city".getBytes(), "jieyang".getBytes());
table.put(put);
// 查询
// get 'students', 'xiaoming', 'info:company'
Get get = new Get("xiaoming".getBytes());
Result result = table.get(get); // 得到的是整条记录
System.out.println(new String(result.getValue(FAMILY_3.getBytes(), "company".getBytes())));
// System.out.println(result);
// 查询全部信息,scan 'students'
Scan scan = new Scan();
ResultScanner scanner = table.getScanner(scan);
for (Result res : scanner) {
System.out.println(res);
}
table.close();
}
}