wiki:waue/2011/0426_4_2

Version 1 (modified by waue, 14 years ago) (diff)

--

ITRI HBase 進階課程
HBase 範例

上一關 < 第二關 > 下一關

範例二: Put 資料進 Column

  • 注意: 若此程式執行於 eclipse ,則方便起見,請將程式的 eclipse only 的後兩行的註解取消
  • 之後的範例有同樣情況就不寫了
$ bin/hadoop jar ItriMenu.jar PutData "ex1Table" "row221" "Detail" "c1" "my value good"

putData.java

package itri;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.GenericOptionsParser;

public class PutData {
  public PutData(String tablename, String row, String family, String column,
      String value) {
    try {
      putData(tablename, row, family, column, value);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  static public void putData(String tablename, String row, String family,
      String column, String value) throws IOException {
    // HBaseConfiguration 能接收 hbase-site.xml 的設定值
    HBaseConfiguration config = new HBaseConfiguration();
    // 檔案的操作則使用 HBaseAdmin
    HTable table = new HTable(config, tablename);

    byte[] brow = Bytes.toBytes(row);
    byte[] bfamily = Bytes.toBytes(family);
    byte[] bcolumn = Bytes.toBytes(column);
    byte[] bvalue = Bytes.toBytes(value);

    Put p = new Put(brow);
    p.add(bfamily, bcolumn, bvalue);

    table.put(p);
    System.out.println("Put data :\"" + value + "\" to Table: " + tablename
        + "'s " + family + ":" + column);

    table.close();
  }

  static public void main(String argv[]) throws IOException {
//    String[] argc = {"t1","r1","f1","c1","v1"};argv = argc;
    
    String[] args = new GenericOptionsParser(new Configuration(), argv)
        .getRemainingArgs();
    if (args.length < 5) {
      System.out.println("PutData <TableName> <Row> <Family> <Qualifier> <Value>");
      return;
    }
    putData(args[0],args[1],args[2],args[3],args[4]);
  }
}

  • 執行結果
    Put data :"my value good" to Table: ex1Table's Detail:c1