天天看點

對HBase資料庫的操縱(MapReduce)

操縱HBase資料庫有如下幾種方式:其一是使用hbase shell,其二是使用Java API,其三是通過MapReduce。另外HBase還提供了Avro,REST和Thrift接口,不過一般用的較少。

在《HBase操作》和[《如何用MapReduce程式操作》]hbase(http://blog.csdn.net/liuyuan185442111/article/details/45306193)中已有部分描述。下面對MapReduce操縱HBase做一個總結。

org.apache.hadoop.hbase.mapreduce包中的類和工具有利于将HBase作為MapReduce作業的源/輸出。

TableInputFormat類将資料表按照region分割成 split,既有多少個regions就有多個splits。然後将region按行鍵分成<key,value>對,key值對應于行健,value值為該行所包含的資料。

org.apache.hadoop.hbase.mapreduce.TableInputFormat
繼承自
org.apache.hadoop.hbase.mapreduce.TableInputFormatBase
後者又繼承自
org.apache.hadoop.mapreduce.InputFormat<ImmutableBytesWritable,Result>

org.apache.hadoop.hbase.mapreduce.TableMapper<KEYOUT,VALUEOUT>
繼承自
org.apache.hadoop.mapreduce.Mapper<ImmutableBytesWritable,Result,KEYOUT,VALUEOUT>
不過<KEYIN,KEYOUT>被固定為<ImmutableBytesWritable,Result>
(org.apache.hadoop.hbase.io.ImmutableBytesWritable)
(org.apache.hadoop.hbase.client.Result)
Mapper的map函數的前兩個參數也被固定:
public void map(ImmutableBytesWritable, Result, Context);
           

如果Mapper需要從HBase中讀取資料,可繼承TableMapper,然後調用TableMapReduceUtil.initTableMapperJob()來初始化。

使用Mapper讀HBase的時候,需傳入一個Scan類型的參數,用來确定startRow,stopRow,filter等屬性。如:

Scan scan = new Scan();
scan.addFamily(Bytes.toBytes("cfname"));
byte[] startRow = Bytes.toBytes("2011010100000");
byte[] stopRow = Bytes.toBytes("2011010200000");
// 設定開始和結束key
scan.setStartRow(startRow);
scan.setStopRow(stopRow);

TableMapReduceUtil.initTableMapperJob("tablename", scan,
Mapper.class, KEYOUT.class, VALUEOUT.class, job);
           

輸出

TableOutputFormat把Reducer的結果寫入HBase。

org.apache.hadoop.hbase.mapreduce.TableReducer<KEYIN,VALUEIN,KEYOUT>
繼承自
org.apache.hadoop.mapreduce.Reducer<KEYIN,VALUEIN,KEYOUT,Mutation>
不過VALUEOUT被固定為org.apache.hadoop.hbase.client.Mutation
Reducer的reduce函數的前兩個參數也被固定:
public void reduce(KEYIN key, Iterable<VALUEIN> values, Context context);
Mutation的直接派生類有Append, Delete, Increment, Put
是以在reduce函數中調用context.write()時, 其第一個參數可以為null(并沒有用到這個參數), 第二個參數可以為Put或Delete
           

如果Reducer需要向HBase中寫入資料,可繼承TableReducer類,然後調用TableMapReduceUtil.initTableReducerJob()來初始化。

org.apache.hadoop.hbase.mapreduce.IdentityTableReducer繼承自TableReducer,Convenience class that simply writes all values (which must be Put or Delete instances) passed to it out to the configured HBase table,傳給IdentityTableReducer的KEY無所謂,VALUE必須是Put或Delete類型。

同時調用setNumReduceTasks函數将Reducer數目設定為0,即可實作在Mapper中寫HBase資料庫。

Put,Delete,Scan,Result均位于org.apache.hadoop.hbase.client中。

繼續閱讀