HBaseAdminDemo 使用客户端api-demo

看到很多关于hbase client 代码都是过时,所以写了一个基于

<dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-shaded-client-project</artifactId>
            <version>1.3.1</version>
</dependency>
package com.eroadsf.hbase.newclient;

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

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.KeyValue;
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.filter.BinaryPrefixComparator;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.QualifierFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueExcludeFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;

public class HBaseAdminDemo {
    public static void main(String[] args) throws IOException {
        Configuration conf = HBaseConfiguration.create();
        Connection connection = ConnectionFactory.createConnection(conf);
        Admin admin = connection.getAdmin();
        // createTable(admin,"emp");
        // listTable(admin,"emp");
        // disableTable(admin,"emp");
        // enableTable(admin,"emp");
        // deleteTable(admin,"emp");
        // listTable(admin);
        // describeTable(admin,"emp");
        // alterTableAddColumnFamily(admin,"emp");
        // deleteColumnFamily(admin,"emp");
        // describeTable(admin,"emp");
        // existsTable(admin,"emp");
        // shutDown(admin);
        // addRecord(connection,"emp");
        // updateRecord(connection, "emp");
        // getRecord(connection, "emp");
        // deleteRecord(connection, "emp");
//       scanRecord(connection, "TraceV2");
//      byte[] bt1 = { 0 };
//      byte[] bt2 = "管理员".getBytes();
//      byte[] bt3 = new byte[bt1.length + bt2.length];
//      System.arraycopy(bt1, 0, bt3, 0, bt1.length);
//      System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        // for(byte a:bt3){
        // System.out.println(a);
        //
        // }
        List<String> arr = new ArrayList<String>();  
        arr.add("S,user,管理员");  
        selectByFilter(connection, "TraceV2", "S", "user", bt3);
        getFilterValue(connection, "TraceV2",arr);
//      selectByRowKey(connection, "TraceV2", Hex.decodeHex("1f7070323031373034323100000000000000000000000000000000015fbeacbf68000000000000001e".toCharArray()));
    }



    public static void createTable(Admin admin, String tablename) throws IOException {
        HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tablename));
        tableDescriptor.addFamily(new HColumnDescriptor("personal"));
        tableDescriptor.addFamily(new HColumnDescriptor("professional"));
        admin.createTable(tableDescriptor);
        System.out.println(" Table created ");
    }

    public static void listTable(Admin admin) throws IOException {
        HTableDescriptor[] tableDescriptor = admin.listTables();
        for (HTableDescriptor d : tableDescriptor) {
            System.out.println(d.getNameAsString());
        }
    }

    public static void disableTable(Admin admin, String tablename) throws IOException {
        admin.disableTables(tablename);
    }

    public static void enableTable(Admin admin, String tablename) throws IOException {
        admin.enableTables(tablename);
    }

    public static void deleteTable(Admin admin, String tablename) throws IOException {
        admin.deleteTables(tablename);
    }

    public static void describeTable(Admin admin, String tablename) throws IOException {
        HTableDescriptor table = admin.getTableDescriptor(TableName.valueOf(tablename));
        System.out.println(table.toString());
    }

    public static void alterTableAddColumnFamily(Admin admin, String tablename) throws IOException {
        HColumnDescriptor columnDescriptor = new HColumnDescriptor("contactDetails");
        admin.addColumn(TableName.valueOf(tablename), columnDescriptor);
    }

    public static void deleteColumnFamily(Admin admin, String tablename) throws IOException {
        admin.deleteColumn(TableName.valueOf(tablename), Bytes.toBytes("contactDetails"));
    }

    public static void existsTable(Admin admin, String tablename) throws IOException {
        boolean exists = admin.tableExists(TableName.valueOf(tablename));
        System.out.println("表:[" + tablename + "]" + (exists ? "存在" : "不存在"));
    }

    public static void shutDown(Admin admin) throws IOException {
        admin.shutdown();
    }

    public static void addRecord(Connection connection, String tablename) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Put p = new Put(Bytes.toBytes("row1"));
        p.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"), Bytes.toBytes("raju"));
        p.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("city"), Bytes.toBytes("hyderabad"));
        p.addColumn(Bytes.toBytes("professional"), Bytes.toBytes("designation"), Bytes.toBytes("manager"));
        p.addColumn(Bytes.toBytes("professional"), Bytes.toBytes("salary"), Bytes.toBytes("50000"));
        table.put(p);
        System.out.println("data inserted");

    }

    public static void updateRecord(Connection connection, String tablename) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Put p = new Put(Bytes.toBytes("row1"));
        p.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"), Bytes.toBytes("raju1"));
        p.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("city"), Bytes.toBytes("hyderabad1"));
        p.addColumn(Bytes.toBytes("professional"), Bytes.toBytes("designation"), Bytes.toBytes("manager1"));
        p.addColumn(Bytes.toBytes("professional"), Bytes.toBytes("salary"), Bytes.toBytes("500001"));
        table.put(p);
        System.out.println("update inserted");

    }

    public static void getRecord(Connection connection, String tablename) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Get get = new Get(Bytes.toBytes("row1"));
        Result result = table.get(get);
        byte[] value = result.getValue(Bytes.toBytes("personal"), Bytes.toBytes("name"));
        byte[] value1 = result.getValue(Bytes.toBytes("personal"), Bytes.toBytes("city"));
        String name = Bytes.toString(value);
        String city = Bytes.toString(value1);
        System.out.println("name: " + name + " city: " + city);

    }

    public static void deleteRecord(Connection connection, String tablename) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Delete delete = new Delete(Bytes.toBytes("row1"));
        delete.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"));
        delete.addFamily(Bytes.toBytes("professional"));
        table.delete(delete);
        table.close();
        System.out.println("data deleted.....");

    }

    public static void scanRecord(Connection connection, String tablename) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Scan scan = new Scan();
        // scan.addColumn(Bytes.toBytes("Info"), Bytes.toBytes("i"));
         scan.addFamily(Bytes.toBytes("S"));
//      scan.addColumn(Bytes.toBytes("S"), Bytes.toBytes("user"));

        ResultScanner scanner = table.getScanner(scan);
        // Reading values from scan result
        for (Result result = scanner.next(); result != null; result = scanner.next()) {
            for (KeyValue kv : result.raw()) {
                byte []a=kv.getValue();
                byte[] b=new byte[a.length-1];
                System.arraycopy(a, 1, b, 0, a.length-1);
                System.out.println("列族["+new String(kv.getFamily())+"]:列名:["+new String(kv.getQualifier())+"]键值["+Hex.encodeHexStr(kv.getKey())+"]值["+new String(b)+"]");
            }
        }
        scanner.close();
    }

    /**
     * get方式,通过rowKey查询
     * 
     * @param tablename
     * @param rowKey
     * @throws IOException
     */
    public static void selectByRowKey(Connection connection, String tablename, byte[] rowKey) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Get g = new Get(rowKey);
        List<Filter> filterList = new ArrayList<Filter>();
        filterList.add(new SingleColumnValueExcludeFilter(Bytes.toBytes("S"), Bytes.toBytes("user"), CompareOp.EQUAL,
                new SubstringComparator("管理员")));
        FilterList fl = new FilterList(filterList);
        g.setFilter(fl);
        g.addFamily(Bytes.toBytes("S"));
        Result r = table.get(g);
        for (KeyValue kv : r.raw()) {
            byte []a=kv.getValue();
            byte[] b=new byte[a.length-1];
            System.arraycopy(a, 1, b, 0, a.length-1);
            System.out.println("列族["+new String(kv.getFamily())+"]:列名:["+new String(kv.getQualifier())+"]键值["+Hex.encodeHexStr(kv.getRow())+"]值["+new String(b)+"]");
        }
    }

    public static QualifierFilter createSpanQualifierFilter() {
        byte indexPrefix = 0;
        BinaryPrefixComparator prefixComparator = new BinaryPrefixComparator(new byte[] {indexPrefix});
        QualifierFilter qualifierPrefixFilter = new QualifierFilter(CompareFilter.CompareOp.EQUAL, prefixComparator);
        return qualifierPrefixFilter;
    }

    /**
     * get方式,通过rowKey、column查询
     * 
     * @param tablename
     * @param rowKey
     * @param column
     * @throws IOException
     */
    public static void selectByRowKeyColumn(Connection connection, String tablename, byte[] rowKey, String column)
            throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        Get g = new Get(rowKey);
        g.addFamily(Bytes.toBytes("S"));
        Result r = table.get(g);
        for (KeyValue kv : r.raw()) {
            System.out.println("value: " + new String(kv.getValue()));
        }
    }

    public static void selectByFilter(Connection connection, String tablename, String family, String column,
            byte[] query) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tablename));
        FilterList filterList = new FilterList();
        Scan s1 = new Scan();
        filterList.addFilter(
                new SingleColumnValueFilter(Bytes.toBytes(family), Bytes.toBytes(column), CompareOp.EQUAL, query));
        // 添加下面这一行后,则只返回指定的cell,同一行中的其他cell不返回
        s1.addColumn(Bytes.toBytes(family), Bytes.toBytes(column));
        s1.setFilter(filterList);
        ResultScanner ResultScannerFilterList = table.getScanner(s1);
        for (Result rr = ResultScannerFilterList.next(); rr != null; rr = ResultScannerFilterList.next()) {
            for (KeyValue kv : rr.list()) {
                System.out.println("column: " + new String(kv.getFamily()) + ":" + new String(kv.getQualifier())
                        + " value: " + new String(kv.getValue()));
            }
        }
    }


    public static void getFilterValue(Connection connection, String tableName, List<String> arr) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        List<Filter> filterList = new ArrayList<Filter>();
        Scan sc = new Scan();
        for (String s : arr) {
            String[] arrS = s.split(",");
            filterList.add(new SingleColumnValueFilter(Bytes.toBytes(arrS[0]), Bytes.toBytes(arrS[1]), CompareOp.EQUAL,
                    new SubstringComparator(arrS[2])));
            filterList.add(new SingleColumnValueExcludeFilter(Bytes.toBytes(arrS[0]), Bytes.toBytes(arrS[1]), CompareOp.EQUAL,
                    new SubstringComparator(arrS[2])));
        }
        FilterList fl = new FilterList(filterList);
        sc.setFilter(fl);
        ResultScanner ResultFilterValue = table.getScanner(sc);
        for (Result r : ResultFilterValue) {
            for (KeyValue kv : r.list()) {
                byte []a=kv.getValue();
                byte[] b=new byte[a.length-1];
                System.arraycopy(a, 1, b, 0, a.length-1);
                System.out.println("列族["+new String(kv.getFamily())+"]:列名:["+new String(kv.getQualifier())+"]键值["+Hex.encodeHexStr(kv.getRow())+"]值["+new String(b)+"]");

            }
        }
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值