wiki:NCHCCloudCourse100929_4_HBEX

Version 5 (modified by waue, 14 years ago) (diff)

--

HBase 進階課程
程式範例練習

回課程大綱 << 第一關 > 下一關

範例一:新增Table

  • 看懂以下程式碼,並成功執行它

CreateTable.java

package org.nchc.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.util.GenericOptionsParser;

public class CreateTable {
  public static void createHBaseTable(String tablename, String family)
      throws IOException {
    // HTableDescriptor 用來描述table的屬性
    HTableDescriptor htd = new HTableDescriptor(tablename);

    // HTableDescriptor 透過 add() 方法來加入Column family
    htd.addFamily(new HColumnDescriptor(family));

    // HBaseConfiguration 能接收 hbase-site.xml 的設定值
    HBaseConfiguration config = new HBaseConfiguration();

    // 檔案的操作則使用 HBaseAdmin
    HBaseAdmin admin = new HBaseAdmin(config);

    // 檢查
    if (admin.tableExists(tablename)) {
      System.out.println("Table: " + tablename + "Existed.");
    } else {
      System.out.println("create new table: " + tablename);

      // 建立
      admin.createTable(htd);
    }
  }

  static public void main(String argv[]) throws IOException {
    // eclipse only
//    String[] args = {"tsmc","Detail"};
//    argv = args;

    String[] otherArgs = new GenericOptionsParser(new Configuration(), argv)
        .getRemainingArgs();
    if (otherArgs.length < 2) {
      System.out.println("CreateTable <newTableName> <Family>");
      return;
    }
    
    String tablename = otherArgs[0];
    String family = otherArgs[1];

    System.out.println("1. create table :" + tablename);

    createHBaseTable(tablename, family);
  }
}