Hadoop學習筆記(十六)---HBase JAVA API

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;


public class Hbase {

    public static final String TABLE_NAME = "users";
    public static final String FAMILY_NAME1 = "info";
    public static final String COLUMN_NAME = "age";

    public static void main(String[] args) throws Throwable {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.rootdir", "hdfs://hadoop0:9000/hbase");
        conf.set("hbase.zookeeper.quorum", "hadoop0");

        HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);

        HTable hTable = new HTable(conf, TABLE_NAME);

        createTable(hBaseAdmin);

        //putRecord(hTable);

        //getRecord(hTable);

        scanRecord(hTable);

//      dropTable(hBaseAdmin);
    }

    //遍歷整個表
    private static void scanRecord(HTable hTable) throws Exception {

        Scan scan = new Scan();
        ResultScanner resultScanner = hTable.getScanner(scan);

        for(Result result : resultScanner) {
            byte[] age = result.getValue(FAMILY_NAME1.getBytes(), COLUMN_NAME.getBytes());
            System.out.println(new String(age));
        }

    }

    //得到某一條記錄
    private static void getRecord(HTable hTable) throws Exception {

        Get get = new Get("xiaoming".getBytes());
        Result result = hTable.get(get);
        byte[] age = result.getValue(FAMILY_NAME1.getBytes(), COLUMN_NAME.getBytes());
        System.out.println(new String(age));

    }

    //往表中存入數據
    private static void putRecord(HTable hTable) throws Exception {

        Put put = new Put("xiaoming".getBytes());
        put.add(FAMILY_NAME1.getBytes(), COLUMN_NAME.getBytes(), "30".getBytes());
        hTable.put(put);

    }

    //刪除表
    private static void dropTable(HBaseAdmin hBaseAdmin) throws Exception {

        if(hBaseAdmin.tableExists(TABLE_NAME)) {
            hBaseAdmin.disableTable(TABLE_NAME);
            hBaseAdmin.deleteTable(TABLE_NAME);
        }

    }

    //創建表
    private static void createTable(HBaseAdmin hBaseAdmin) throws Throwable {

        if(!hBaseAdmin.tableExists(TABLE_NAME)) {
            HTableDescriptor hTableDescriptor = new HTableDescriptor(TABLE_NAME);
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(FAMILY_NAME1);
            hTableDescriptor.addFamily(hColumnDescriptor);
            hBaseAdmin.createTable(hTableDescriptor);
        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章