1. 程式人生 > >Hbase例項之建立一個列簇

Hbase例項之建立一個列簇

關於HBase的前後因果先不討論,現在寫一個Hbase例項,怎麼樣去建立一個Hbase的列簇.

public class HbaseTable {

//定義一個hbase連線
Configuration conf = null;

        //構造方法初始化,連線到hbase資料庫
HbaseIf() {
                //建立Hbase資料庫的連線,預設本地
conf=HBaseConfiguration.create();
}
       //建立一個Table
public void create_table(String name, String col, int version)
throws Exception {
                //建立一個物件,連線到Hbase
HBaseAdmin admin = new HBaseAdmin(conf);
                //判斷一個Tbale是否存在,若存在,則刪除該Table
if (admin.tableExists(name)) {
admin.disableTable(name);
admin.deleteTable(name);
}
                //初始化Tbale,傳入Table名稱
HTableDescriptor htd = new HTableDescriptor(name);
                               //初始化列,傳入列名稱
HColumnDescriptor hcd = new HColumnDescriptor(col);
               //設定Hbase最大版本號
hcd.setMaxVersions(1);
               //網一個Table中插入一個列簇
htd.addFamily(hcd);
               //建立一個Tbale
admin.createTable(htd);
}
/*
* tab_global param:userid

* tab_user2id info:id

* tab_id2user info:username, info:password
*/
public void createTables() throws Exception {
                //建立一個名為tab_global的Table,列為param的列
       create_table("tab_global","param",1);
                //建立一個名為row_userid的RowKey,Hbase都是村二進位制的資料所以要轉化的Byte
Put put=new Put(Bytes.toBytes("row_userid"));
int i=1;
                //在列簇中建立一條資料,列簇名是param:userid
                put.add(Bytes.toBytes("param"), Bytes.toBytes("userid"), Bytes.toBytes(i));
//往Table裡插入資料
                HTable ht=new HTable(conf,"tab_global");
                ht.put(put);
                //建立一個名為tab_user2id的Table,列為info的列
                create_table("tab_user2id","info",1);
                create_table("tab_id2user","info",1);
}
public static void main(String[] args) throws Exception {
HbaseTable hbase=new HbaseTable();
hbase.createTables();
}
} 執行該物件資料即可插入。

驗證:在hbase shell中輸入 list 會出現三個表

tab_global                                                                      
tab_id2user                                                                     
tab_user2id  

輸入:scan 'tab_global'  會出現插入的資料

hbase(main):002:0> scan 'tab_global'
ROW                   COLUMN+CELL                                               
 row_userid           column=param:userid, timestamp=1377096845757, value=\x00\x00\x00\x01   

如圖: