HBase MapReduce讀寫示例

2018-04-09 13:42 更新

HBase MapReduce讀寫示例

以下是使用 HBase 作為 MapReduce 的源代碼和接收器的示例。這個(gè)例子將簡(jiǎn)單地將數(shù)據(jù)從一個(gè)表復(fù)制到另一個(gè)表。

Configuration config = HBaseConfiguration.create();
Job job = new Job(config,"ExampleReadWrite");
job.setJarByClass(MyReadWriteJob.class);    // class that contains mapper

Scan scan = new Scan();
scan.setCaching(500);        // 1 is the default in Scan, which will be bad for MapReduce jobs
scan.setCacheBlocks(false);  // don't set to true for MR jobs
// set other scan attrs

TableMapReduceUtil.initTableMapperJob(
  sourceTable,      // input table
  scan,             // Scan instance to control CF and attribute selection
  MyMapper.class,   // mapper class
  null,             // mapper output key
  null,             // mapper output value
  job);
TableMapReduceUtil.initTableReducerJob(
  targetTable,      // output table
  null,             // reducer class
  job);
job.setNumReduceTasks(0);

boolean b = job.waitForCompletion(true);
if (!b) {
    throw new IOException("error with job!");
}

需要解釋的是 TableMapReduceUtil 正在做什么,特別是對(duì)于減速器。TableOutputFormat 被用作 outputFormat 類,并且正在配置幾個(gè)參數(shù)(例如,TableOutputFormat.OUTPUT_TABLE),以及將 reducer 輸出鍵設(shè)置為 ImmutableBytesWritable 和 reducer 值為 Writable。這些可以由程序員在作業(yè)和 conf 中設(shè)置,但 TableMapReduceUtil 試圖讓事情變得更容易。

以下是示例映射器,它將創(chuàng)建 Put 并匹配輸入 Result 并發(fā)出它。注意:這是 CopyTable 實(shí)用程序的功能。

public static class MyMapper extends TableMapper<ImmutableBytesWritable, Put>  {

  public void map(ImmutableBytesWritable row, Result value, Context context) throws IOException, InterruptedException {
    // this example is just copying the data from the source table...
      context.write(row, resultToPut(row,value));
    }

    private static Put resultToPut(ImmutableBytesWritable key, Result result) throws IOException {
      Put put = new Put(key.get());
      for (KeyValue kv : result.raw()) {
        put.add(kv);
      }
      return put;
    }
}

實(shí)際上并沒有一個(gè)簡(jiǎn)化步驟,所以 TableOutputFormat 負(fù)責(zé)將 Put 發(fā)送到目標(biāo)表。

這只是一個(gè)例子,開發(fā)人員可以選擇不使用 TableOutputFormat 并連接到目標(biāo)表本身。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)