1. 程式人生 > >Hbase增刪查改等操作的java客戶端實現

Hbase增刪查改等操作的java客戶端實現


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
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;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;

public class HBaseDemo {

    // 與HBase資料庫的連線物件
    Connection connection;

    // 資料庫元資料操作物件
    Admin admin;

    @Before
    public void setUp() throws Exception {

        // 取得一個數據庫連線的配置引數物件
        Configuration conf = HBaseConfiguration.create();

        // 設定連線引數:HBase資料庫所在的主機IP
        conf.set("hbase.zookeeper.quorum", "192.168.137.13");
        // 設定連線引數:HBase資料庫使用的埠
        conf.set("hbase.zookeeper.property.clientPort", "2181");

        // 取得一個數據庫連線物件
        connection = ConnectionFactory.createConnection(conf);

        // 取得一個數據庫元資料操作物件
        admin = connection.getAdmin();
    }

    /**
     * 建立表
     */
    public void createTable() throws IOException{

        System.out.println("---------------建立表 START-----------------");

        // 資料表表名
        String tableNameString = "t_book";

        // 新建一個數據表表名物件
        TableName tableName = TableName.valueOf(tableNameString);

        // 如果需要新建的表已經存在
        if(admin.tableExists(tableName)){

            System.out.println("表已經存在!");
        }
        // 如果需要新建的表不存在
        else{

            // 資料表描述物件
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);

            // 列族描述物件
            HColumnDescriptor family= new HColumnDescriptor("base");;

            // 在資料表中新建一個列族
            hTableDescriptor.addFamily(family);

            // 新建資料表
            admin.createTable(hTableDescriptor);
        }

        System.out.println("---------------建立表 END-----------------");
    }

    /**
     * 查詢整表資料
     */
     @Test
     public void queryTable() throws IOException{

        System.out.println("---------------查詢整表資料 START-----------------");

        // 取得資料表物件
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 取得表中所有資料
        ResultScanner scanner = table.getScanner(new Scan());

        // 迴圈輸出表中的資料
        for (Result result : scanner) {

            byte[] row = result.getRow();
            System.out.println("row key is:" + new String(row));

            List<Cell> listCells = result.listCells();
            for (Cell cell : listCells) {

                byte[] familyArray = cell.getFamilyArray();
                byte[] qualifierArray = cell.getQualifierArray();
                byte[] valueArray = cell.getValueArray();

                System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) 
                                                                             + new String(valueArray));
            }
        }

        System.out.println("---------------查詢整表資料 END-----------------");

    }

    /**
     * 按行鍵查詢表資料
     */
     @Test
    public void queryTableByRowKey() throws IOException{

        System.out.println("---------------按行鍵查詢表資料 START-----------------");

        // 取得資料表物件
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 新建一個查詢物件作為查詢條件
        Get get = new Get("row8".getBytes());

        // 按行鍵查詢資料
        Result result = table.get(get);

        byte[] row = result.getRow();
        System.out.println("row key is:" + new String(row));

        List<Cell> listCells = result.listCells();
        for (Cell cell : listCells) {

            byte[] familyArray = cell.getFamilyArray();
            byte[] qualifierArray = cell.getQualifierArray();
            byte[] valueArray = cell.getValueArray();

            System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) 
                                                                         + new String(valueArray));
        }

        System.out.println("---------------按行鍵查詢表資料 END-----------------");

    }

    /**
     * 按條件查詢表資料
     */
     @Test
    public void queryTableByCondition() throws IOException{

        System.out.println("---------------按條件查詢表資料 START-----------------");

        // 取得資料表物件
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 建立一個查詢過濾器
        Filter filter = new SingleColumnValueFilter(Bytes.toBytes("base"), Bytes.toBytes("name"), 
                                                    CompareOp.EQUAL, Bytes.toBytes("bookName6"));

        // 建立一個數據表掃描器
        Scan scan = new Scan();

        // 將查詢過濾器加入到資料表掃描器物件
        scan.setFilter(filter);

        // 執行查詢操作,並取得查詢結果
        ResultScanner scanner = table.getScanner(scan);

        // 迴圈輸出查詢結果
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("row key is:" + new String(row));

            List<Cell> listCells = result.listCells();
            for (Cell cell : listCells) {

                byte[] familyArray = cell.getFamilyArray();
                byte[] qualifierArray = cell.getQualifierArray();
                byte[] valueArray = cell.getValueArray();

                System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) 
                                                                             + new String(valueArray));
            }
        }

        System.out.println("---------------按條件查詢表資料 END-----------------");

    }

    /**
     * 清空表
     */
    @Test
    public void truncateTable() throws IOException{

        System.out.println("---------------清空表 START-----------------");

        // 取得目標資料表的表名物件
        TableName tableName = TableName.valueOf("t_book");

        // 設定表狀態為無效
        admin.disableTable(tableName);
        // 清空指定表的資料
        admin.truncateTable(tableName, true);

        System.out.println("---------------清空表 End-----------------");
    }

    /**
     * 刪除表
     */
    @Test
    public void deleteTable() throws IOException{

        System.out.println("---------------刪除表 START-----------------");

        // 設定表狀態為無效
        admin.disableTable(TableName.valueOf("t_book"));
        // 刪除指定的資料表
        admin.deleteTable(TableName.valueOf("t_book"));

        System.out.println("---------------刪除表 End-----------------");
    }

    /**
     * 刪除行
     */
    @Test
    public void deleteByRowKey() throws IOException{

        System.out.println("---------------刪除行 START-----------------");

        // 取得待操作的資料表物件
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 建立刪除條件物件
        Delete delete = new Delete(Bytes.toBytes("row2"));

        // 執行刪除操作
        table.delete(delete);

        System.out.println("---------------刪除行 End-----------------");

    }

    /**
     * 刪除行(按條件)
     */
    @Test
    public void deleteByCondition() throws IOException, DeserializationException{

        System.out.println("---------------刪除行(按條件) START-----------------");

        // 步驟1:呼叫queryTableByCondition()方法取得需要刪除的資料列表 

        // 步驟2:迴圈步驟1的查詢結果,對每個結果呼叫deleteByRowKey()方法

        System.out.println("---------------刪除行(按條件) End-----------------");

    }

    /**
     * 新建列族
     */
    @Test
    public void addColumnFamily() throws IOException{

        System.out.println("---------------新建列族 START-----------------");

        // 取得目標資料表的表名物件
        TableName tableName = TableName.valueOf("t_book");

        // 建立列族物件
        HColumnDescriptor columnDescriptor = new HColumnDescriptor("more");

        // 將新建立的列族新增到指定的資料表
        admin.addColumn(tableName, columnDescriptor);

        System.out.println("---------------新建列族 END-----------------");
    }

    /**
     * 刪除列族
     */
    @Test
    public void deleteColumnFamily() throws IOException{

        System.out.println("---------------刪除列族 START-----------------");

        // 取得目標資料表的表名物件
        TableName tableName = TableName.valueOf("t_book");

        // 刪除指定資料表中的指定列族
        admin.deleteColumn(tableName, "more".getBytes());

        System.out.println("---------------刪除列族 END-----------------");
    }

    /**
     * 插入資料
     */
    @Test
    public void insert() throws IOException{

        System.out.println("---------------插入資料 START-----------------");

        // 取得一個數據表物件
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 需要插入資料庫的資料集合
        List<Put> putList = new ArrayList<Put>();

        Put put;

        // 生成資料集合
        for(int i = 0; i < 10; i++){
            put = new Put(Bytes.toBytes("row" + i));
            put.addColumn(Bytes.toBytes("base"), Bytes.toBytes("name"), Bytes.toBytes("bookName" + i));

            putList.add(put);
        }

        // 將資料集合插入到資料庫
        table.put(putList);

        System.out.println("---------------插入資料 END-----------------");
    }

}