HBase 2.0 API 初步窥探

本文深入浅出地介绍了HBase 2.0的API使用,通过实例代码展示了如何进行数据操作,包括插入、查询、更新和删除等核心功能,帮助读者快速理解HBase 2.0的新特性。
摘要由CSDN通过智能技术生成

话不多说直接上代码

package Base;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;

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

public class TestBasicOption {
    static Configuration config = null;
    static {
        config = HBaseConfiguration.create();
    }

    /**
     * @throws IOException
     * 创建单列簇的表
     */
    @Test
    public void createTable() throws IOException {
        try (Connection conn = ConnectionFactory.createConnection(config);
             Admin admin = conn.getAdmin()) {
            TableName tableName = TableName.valueOf("base1");
            if (!admin.tableExists(tableName)){
                // 表描述器的构建器
                TableDescriptorBuilder tdb = TableDescriptorBuilder.newBuilder(tableName);
                //  tdb.set...  可以设置表属性
                // 列簇描述器的构建器
                ColumnFamilyDescriptorBuilder cfdb = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"));
                //  cfdb.set...可以设置列簇属性
                //  列簇描述器
                ColumnFamilyDescriptor cfd = cfdb.build();
                //  将列簇描述器添加到表描述器构造器
                tdb.setColumnFamily(cfd);
                //  获得带有列簇描述器的表描述器
                TableDescriptor td = tdb.build();
                //  将表描述器传入admin管理者,创建表
                admin.createTable(td);
            }else{
                System.out.println("表已经存在!");
            }
        }
    }

    /**
     * @throws IOException
     * 创建包含多个列簇的表
     */
    @Test
    public void createTableWithMutl() throws IOException {
        try (Connection conn = ConnectionFactory.createConnection(config);
             Admin admin = conn.getAdmin()) {
            TableName tableName = TableName.valueOf("base2");
            if (!admin.tableExists(tableName)){
                TableDescriptorBuilder tdb = TableDescriptorBuilder.newBuilder(tableName);
                ColumnFamilyDescriptorBuilder cfdb1 = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("into1"));
                ColumnFamilyDescriptor cfd1 = cfdb1.build();
                ColumnFamilyDescriptorBuilder cfdb2 = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("into2"));
                ColumnFamilyDescriptor cfd2 = cfdb2.build();
                //  创建列簇描述器的列表
                List<ColumnFamilyDescriptor> cfdList = new ArrayList<>();
                //  添加每个列簇描述器于列表中
                cfdList.add(cfd1);
                cfdList.add(cfd2);
                //  将列簇描述器列表对象传入表描述器构建器对象
                tdb.setColumnFamilies(cfdList);
                //  得到包含多个列簇信息的表描述器
                TableDescriptor td = tdb.build();
                //  创建该表
                admin.createTable(td);
            }else{
                System.out.println("表已经存在!");
            }
        }
    }

    /**
     * @throws IOException
     * 向已有表中添加列簇
     * 对已有表的列簇进行属性修改,这里以修改版本最大值为例子
     */
    @Test
    public void modifyColumnFamily() throws IOException {
        /*
        原表概况:
        hbase(main):019:0> desc 'base1'
        COLUMN FAMILIES DESCRIPTION
        {NAME => 'info', VERSIONS => '1', EVICT_BLOCKS_ON_CLOSE => 'false', NEW_VERSION_BEHAVIOR => 'false', KEEP_DELETED_CELLS => 'FALSE', CACHE_DATA_ON_WRITE => 'false', DATA_BLOCK_ENCODING => 'NONE', TTL => 'FOREVE
        R', MIN_VERSIONS => '0', REPLICATION_SCOPE => '0', BLOOMFILTER => 'ROW', CACHE_INDEX_ON_WRITE => 'false', IN_MEMORY => 'false', CACHE_BLOOMS_ON_WRITE => 'false', PREFETCH_BLOCKS_ON_OPEN => 'false', COMPRESSION
         => 'NONE', BLOCKCACHE => 'true', BLOCKSIZE => '65536'}
        1 row(s)
         */
        try(Connection conn = ConnectionFactory.createConnection(config);
            Admin admin = conn.getAdmin()){
            TableName tableName = TableName.valueOf("base1");
            if(admin.tableExists(tableName)){
                ColumnFamilyDescriptorBuilder newcfdb = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info111"));
                ColumnFamilyDescriptor newcdb = newcfdb.build();
                admin.addColumnFamily(tableName,newcdb);

                ColumnFamilyDescriptorBuilder oldcfdb = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"));
                oldcfdb.setMaxVersions(10);
                ColumnFamilyDescriptor modifiedCDB = oldcfdb.build();
                admin.modifyColumnFamily(tableName,modifiedCDB);
            }else{
                System.out.println("该表不存在");
            }
        }
        /*
        以上代码执行完毕后,表概况如下:
        hbase(main):020:0> desc 'base1'
        COLUMN FAMILIES DESCRIPTION
        {NAME => 'info', VERSIONS => '10', EVICT_BLOCKS_ON_CLOSE => 'false', NEW_VERSION_BEHAVIOR => 'false', KEEP_DELETED_CELLS => 'FALSE', CACHE_DATA_ON_WRITE => 'false', DATA_BLOCK_ENCODING => 'NONE', TTL => 'FOREV
        ER', MIN_VERSIONS => '0', REPLICATION_SCOPE => '0', BLOOMFILTER => 'ROW', CACHE_INDEX_ON_WRITE => 'false', IN_MEMORY => 'false', CACHE_BLOOMS_ON_WRITE => 'false', PREFETCH_BLOCKS_ON_OPEN => 'false', COMPRESSIO
        N => 'NONE', BLOCKCACHE => 'true', BLOCKSIZE => '65536'}
        {NAME => 'info111', VERSIONS => '1', EVICT_BLOCKS_ON_CLOSE => 'false', NEW_VERSION_BEHAVIOR => 'false', KEEP_DELETED_CELLS => 'FALSE', CACHE_DATA_ON_WRITE => 'false', DATA_BLOCK_ENCODING => 'NONE', TTL => 'FOR
        EVER', MIN_VERSIONS => '0', REPLICATION_SCOPE => '0', BLOOMFILTER => 'ROW', CACHE_INDEX_ON_WRITE => 'false', IN_MEMORY => 'false', CACHE_BLOOMS_ON_WRITE => 'false', PREFETCH_BLOCKS_ON_OPEN => 'false', COMPRESS
        ION => 'NONE', BLOCKCACHE => 'true', BLOCKSIZE => '65536'}
        2 row(s)
        */
    }

    /**
     * @throws IOException
     * 向存在的表中添加数据
     */
    @Test
    public void putData() throws IOException {
        try(Connection conn = ConnectionFactory.createConnection(config);
            Admin admin = conn.getAdmin()){
            //  得到表对象,用来操作表中数据
            TableName tableName = TableName.valueOf("base1");
            if(admin.tableExists(tableName)){
                Table table = conn.getTable(tableName);
                //  插入一条数据
                Put put1 = new Put(Bytes.toBytes("001"));
                put1.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("zhangsan"));
                table.put(put1);

                //  插入多条数据,有些数据包含多个列
                List<Put> putList = new ArrayList<>();
                Put put2 = new Put(Bytes.toBytes("002"));
                put2.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("lisi"));
                Put put3 = new Put(Bytes.toBytes("003"));
                put3.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("wangwu"));
                put3.addColumn(Bytes.toBytes("info"),Bytes.toBytes("age"),Bytes.toBytes(23));
                Put put4 = new Put(Bytes.toBytes("004"));
                put4.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("zhaoliu"));
                put4.addColumn(Bytes.toBytes("info"),Bytes.toBytes("age"),Bytes.toBytes(17));
                put4.addColumn(Bytes.toBytes("info"),Bytes.toBytes("school"),Bytes.toBytes("HomeDun"));
                putList.add(put2);
                putList.add(put3);
                putList.add(put4);
                table.put(putList);
                table.close();
            }else{
                System.out.println("该表不存在");
            }
            /*
            hbase(main):023:0> scan 'base1'
            ROW                                                   COLUMN+CELL
             001                                                  column=info:name, timestamp=1564215173039, value=zhangsan
             002                                                  column=info:name, timestamp=1564215173244, value=lisi
             003                                                  column=info:age, timestamp=1564215173244, value=\x00\x00\x00\x17
             003                                                  column=info:name, timestamp=1564215173244, value=wangwu
             004                                                  column=info:age, timestamp=1564215173244, value=\x00\x00\x00\x11
             004                                                  column=info:name, timestamp=1564215173244, value=zhaoliu
             004                                                  column=info:school, timestamp=1564215173244, value=HomeDun
             */
        }
    }

    /**
     * @throws IOException
     * 修改某条记录的某个列的值
     *      实质就是将新的值作为新的版本添加,并没有真正替换,原来的值存在老版本的单元格中
     */
    @Test
    public void modifyColumnValue() throws IOException {
        try(Connection conn = ConnectionFactory.createConnection(config);
            Admin admin = conn.getAdmin()) {
            //  得到表对象,用来操作表中数据
            TableName tableName = TableName.valueOf("base1");
            if (admin.tableExists(tableName)) {
                Table table = conn.getTable(tableName);
                Put put4 = new Put(Bytes.toBytes("004"));
                put4.addColumn(Bytes.toBytes("info"),Bytes.toBytes("school"),Bytes.toBytes("MiddleSchool"));
                table.put(put4);
                table.close();
            }else{
                System.out.println("该表不存在");
            }
        }
        /*
         004       column=info:age, timestamp=1564215173244, value=\x00\x00\x00\x11
         004       column=info:name, timestamp=1564215173244, value=zhaoliu
         004       column=info:school, timestamp=1564215469986, value=MiddleSchool
         */
    }

    @Test
    public void deleteData() throws IOException {
        try(Connection conn = ConnectionFactory.createConnection(config);
            Admin admin = conn.getAdmin()) {
            //  得到表对象,用来操作表中数据
            TableName tableName = TableName.valueOf("base1");
            if (admin.tableExists(tableName)) {
                /*
                删除前:
                 002      column=info:name, timestamp=1564215173244, value=lisi
                 001      column=info:name, timestamp=1564215173039, value=zhangsan
                 003      column=info:age, timestamp=1564215173244, value=\x00\x00\x00\x17
                 003      column=info:name, timestamp=1564215173244, value=wangwu
                 004      column=info:age, timestamp=1564215173244, value=\x00\x00\x00\x11
                 004      column=info:name, timestamp=1564215173244, value=zhaoliu
                 004      column=info:school, timestamp=1564215469986, value=MiddleSchool
                 */
                Table table = conn.getTable(tableName);
                //  删除一行内容
                Delete delete1 = new Delete(Bytes.toBytes("001"));
                table.delete(delete1);

                //  删除某一行一个列簇内容
                Delete delete2 = new Delete(Bytes.toBytes("003"));
                delete2.addFamily(Bytes.toBytes("info"));
                table.delete(delete2);

                //  删除某一行某一列簇某些值的内容
                Delete delete3 = new Delete(Bytes.toBytes("004"));
                delete3.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"));
                delete3.addColumn(Bytes.toBytes("info"),Bytes.toBytes("school"));
                table.delete(delete3);

                table.close();
            }else{
                System.out.println("该表不存在");
            }
            /*
            删除后:
             002             column=info:name, timestamp=1564215173244, value=lisi
             004             column=info:age, timestamp=1564215173244, value=\x00\x00\x00\x11
             004             column=info:school, timestamp=1564215173244, value=HomeDun
             由于对于003来说只有一个列簇,删除整个列簇的数据后,该记录也相当于删除了
             */
        }
    }


    /**
     * @throws IOException
     * 按照rowKey得到某条记录
     */
    @Test
    public void getData() throws IOException {
        //  这里简单写异常处理的内容了
        Connection conn = ConnectionFactory.createConnection(config);
        Table table = conn.getTable(TableName.valueOf("base1"));
        Get get = new Get(Bytes.toBytes("004"));
        Result result = table.get(get);
        for(Cell cell : result.rawCells()){
            System.out.println(Bytes.toString(CellUtil.cloneRow(cell)));
            System.out.println(Bytes.toString(CellUtil.cloneFamily(cell)));
            System.out.println(Bytes.toString(CellUtil.cloneQualifier(cell)));
            System.out.println(Bytes.toString(CellUtil.cloneValue(cell)));
        }
        table.close();
        conn.close();
    }

    /**
     * @throws IOException
     * 全表扫描,得到数据
     */
    @Test
    public void scanData() throws IOException {
        //  这里简单写异常处理的内容了
        Connection conn = ConnectionFactory.createConnection(config);
        Table table = conn.getTable(TableName.valueOf("base1"));
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            for (Cell cell : result.listCells()) {
                if (Bytes.toString(CellUtil.cloneQualifier(cell)).equals("age")) {
                    System.out.println("求不乱码");
                    System.out.print(Bytes.toString(CellUtil.cloneRow(cell)) + "\t\t");
                    System.out.print(Bytes.toString(CellUtil.cloneFamily(cell)) + ":");
                    System.out.print(Bytes.toString(CellUtil.cloneQualifier(cell)) + " -> ");
                    System.out.println(Bytes.toInt(CellUtil.cloneValue(cell)));
                } else {
                    System.out.println("叫你不用String");
                    System.out.print(Bytes.toString(CellUtil.cloneRow(cell)) + "\t\t");
                    System.out.print(Bytes.toString(CellUtil.cloneFamily(cell)) + ":");
                    System.out.print(Bytes.toString(CellUtil.cloneQualifier(cell)) + " -> ");
                    System.out.println(Bytes.toString(CellUtil.cloneValue(cell)));
                }
            }
            /*
            叫你不用String
            001		info:name -> zhangsan
            叫你不用String
            002		info:name -> lisi
            求不乱码
            003		info:age -> 23
            叫你不用String
            003		info:name -> wangwu
            求不乱码
            004		info:age -> 17
            叫你不用String
            004		info:name -> zhaoliu
            叫你不用String
            004		info:school -> HomeDun          
             */
            table.close();
            conn.close();
        }

    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值