Java對Hbase的各種操作都是通過HTable實現的,由於建立HTable是有消耗的,因此推薦只建立一個HTable的執行個體,如果必須使用多個HTable執行個體,可以使用HTablePool,本文不對HTablePool進行介紹。
建立表:
建立表是通過HBaseAdmin類實現的,通過HBaseAdmin 類主要是對於表的管理操作。
1 public static void createTable(String tableName, String[] cfs) throws IOException{ 2 HBaseAdmin admin = new HBaseAdmin(configuration); 3 if (admin.tableExists(tableName)) { 4 System.out.println("table already exists"); 5 }else { 6 HTableDescriptor descriptor = new HTableDescriptor(tableName); 7 for(int i = 0; i < cfs.length; ++i){ 8 descriptor.addFamily(new HColumnDescriptor(cfs[i])); 9 }10 admin.createTable(descriptor);11 }12 }
HBaseAdmin還包含了各種動作表的API,包括刪除表,刪除列等,有興趣的可以看他的官方API,這裡就不再討論了。
添加資料:
添加資料通過HTable的put操作,添加Put對象;
void put(Put put) throws IOException
對於Put類,包含了多個建構函式使用,在這裡我們只是使用了他的第一個建構函式。
Put(byte[] row)Put(byte[] row, RowLock rowLock)Put(byte[] row, long ts)Put(byte[] row, long ts, RowLock rowLock)
像Put對象添加資料使用add函數:
Put add(byte[] family, byte[] qualifier, byte[] value)Put add(byte[] family, byte[] qualifier, long ts, byte[] value)Put add(KeyValue kv) throws IOException
添加資料操作:
1 public static void putData(String tableName) throws IOException{2 HTable table = new HTable(configuration, tableName);3 Put put = new Put(Bytes.toBytes("row1"));4 put.add(Bytes.toBytes("cf"), Bytes.toBytes("a"), Bytes.toBytes("v1"));5 table.put(put);6 table.close();7 }
擷取資料:
對於擷取資料,需要喜歡使用HTable的get函數:
Result get(Get get) throws IOException
Get類的建構函式相對與Put少了ts
Get(byte[] row)Get(byte[] row, RowLock rowLock)
擷取資料的操作:
1 public static void getData(String tableName) throws IOException{2 HTable table = new HTable(configuration, tableName);3 Get get = new Get(Bytes.toBytes("row1"));4 Result result = table.get(get);5 String value = new String(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("a")));6 System.out.println(value);7 table.close();8 }
對於掃描全表則需要使用scanner了。
public static void scannerData(String tablename) throws IOException { HTable table = new HTable(configuration, tablename); Scan s = new Scan(); ResultScanner rs = table.getScanner(s); for (Result r : rs) { KeyValue[] kv = r.raw(); for (int i = 0; i < kv.length; i++) { System.out.print(new String(kv[i].getRow()) + " "); System.out.print(new String(kv[i].getFamily()) + ":"); System.out.print(new String(kv[i].getQualifier()) + " "); System.out.print(kv[i].getTimestamp() + " "); System.out.println(new String(kv[i].getValue())); } } }