表格存储服务 CLOUDTABLE-创建表:代码样例

时间:2023-11-10 14:32:20

代码样例

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)”。

support.huaweicloud.com/devg-cloudtable/cloudtable_01_0279.html