wiki:waue/2011/0426_4

Version 3 (modified by waue, 13 years ago) (diff)

--

HBase 進階課程
HBase 範例

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

注意

  • 請將以下給個 hbase 重要的檔複製到 hadoop lib 目錄下,並且重新啟動 hbase 與 hadoop
$ cd /opt/hbase
$ cp hbase-*.jar lib/zookeeper-3.2.2.jar contrib/transactional/hbase-*-transactional.jar /opt/hadoop/lib/
$ /opt/hbase/bin/stop-hbase.sh
$ /opt/hadoop/bin/stop-all.sh
$ /opt/hadoop/bin/start-all.sh
$ /opt/hbase/bin/start-hbase.sh
  • 若編譯以下範例的環境為console 端,請設定完整的classpath,詳細方法請看教材投影片
  • 若開發是透過 eclipse ,請將 hbase-core.jar , zookeeper*.jar , hbase-*-transactional.jar 匯入到 project library 中,詳細方法請看教材投影片
  • 注意: 若此程式執行於 eclipse ,則方便起見,請將程式的 eclipse only 的後兩行的註解取消,如:
    // eclipse only
    String[] args = {"ex1Table","Detail"};
    argv = args;

範例一:新增Table

bin/hadoop jar NCHCMenu.jar CreateTable ex1Table Detail

CreateTable.java

package nchc;

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 contains the name of an HTable, and its column
    // families
    // HTableDescriptor 用來描述table的屬性
    HTableDescriptor htd = new HTableDescriptor(tablename);
    // HColumnDescriptor HColumnDescriptor contains information about a
    // column family such as the number of versions, compression settings,
    // etc.
    // 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 {
//    String[] argc = {"t1","f1"};argv = argc;
    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);
  }
}

  • 執行結果
1. create table :ex1Table
ex1Table created.