更新时间:2023-11-10 GMT+08:00
分享

创建表

功能介绍

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 hot and cold data boundary
  hcd.setValue(HColumnDescriptor.COLD_BOUNDARY, "86400");
  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); // 注[1] (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应用。

      注[1] 指的是代码样例中的“admin.createTable(htd); // 注[1] (5)”。

分享:

    相关文档

    相关产品