创建表
功能简介
HBase通过org.apache.hadoop.hbase.client.Admin对象的createTable方法来创建表,并指定表名、列族名。创建表有两种方式(强烈建议采用预分Region建表方式):
- 快速建表,即创建表后整张表只有一个Region,随着数据量的增加会自动分裂成多个Region。
- 预分Region建表,即创建表时预先分配多个Region,此种方法建表可以提高写入大量数据初期的数据写入速度。
说明:
表的列名以及列族名不能包含特殊字符,可以由字母、数字以及下划线组成。
代码样例
public void testCreateTable() {
LOG.info("Entering testCreateTable.");
// Specify the table descriptor.
HTableDescriptor htd = new HTableDescriptor(tableName); (1)
// Set the column family name to info.
HColumnDescriptor hcd = new HColumnDescriptor("info"); (2)
// Set data encoding methods, HBase provides DIFF,FAST_DIFF,PREFIX
// and PREFIX_TREE
hcd.setDataBlockEncoding(DataBlockEncoding.FAST_DIFF);
// Set compression methods, HBase provides two default compression
// methods:GZ and SNAPPY
// GZ has the highest compression rate,but low compression and
// decompression effeciency,fit for cold data
// SNAPPY has low compression rate, but high compression and
// decompression effeciency,fit for hot data.
// it is advised to use SNAANPPY
hcd.setCompressionType(Compression.Algorithm.SNAPPY);//注[1]
htd.addFamily(hcd); (3)
Admin admin = null;
try {
// Instantiate an Admin object.
admin = conn.getAdmin(); (4)
if (!admin.tableExists(tableName)) {
LOG.info("Creating table...");
admin.createTable(htd);//注[2] (5)
LOG.info(admin.getClusterStatus());
LOG.info(admin.listNamespaceDescriptors());
LOG.info("Table created successfully.");
} else {
LOG.warn("table already exists");
}
} catch (IOException e) {
LOG.error("Create table failed " ,e);
} finally {
if (admin != null) {
try {
// Close the Admin object.
admin.close();
} catch (IOException e) {
LOG.error("Failed to close admin " ,e);
}
}
}
LOG.info("Exiting testCreateTable.");
}
解释
(1)创建表描述符
(2)创建列族描述符
(3)添加列族描述符到表描述符中
(4)获取Admin对象,Admin提供了建表、创建列族、检查表是否存在、修改表结构和列族结构以及删除表等功能。
(5)调用Admin的建表方法。
注意事项
- 注[1] 可以设置列族的压缩方式,代码片段如下:
//设置编码算法,HBase提供了DIFF,FAST_DIFF,PREFIX和PREFIX_TREE四种编码算法
hcd.setDataBlockEncoding(DataBlockEncoding.FAST_DIFF);
//设置文件压缩方式,HBase默认提供了GZ和SNAPPY两种压缩算法
//其中GZ的压缩率高,但压缩和解压性能低,适用于冷数据
//SNAPPY压缩率低,但压缩解压性能高,适用于热数据
//建议默认开启SNAPPY压缩
hcd.setCompressionType(Compression.Algorithm.SNAPPY);
- 注[2] 可以通过指定起始和结束RowKey,或者通过RowKey数组预分Region两种方式建表,代码片段如下:
// 创建一个预划分region的表
byte[][] splits = new byte[4][];
splits[0] = Bytes.toBytes("A");
splits[1] = Bytes.toBytes("H");
splits[2] = Bytes.toBytes("O");
splits[3] = Bytes.toBytes("U");
admin.createTable(htd, splits);