大数据开发HBase Java Api操作(第二十四篇)

469 阅读4分钟

一、HBase的增删改查操作

命令解释
put添加数据、修改数据
get查看数据
count查看表中数据总条数
scan扫描表中的数据
delete/deleteall删除数据
1.1、添加数据

put 'namespace:表','rowkey','列族1:列名1','值'

image-20221030205852363

image-20221030205952602

1.2、查看数据

get 'namespace:表名','rowkey'

image-20221030210052715

获取某个列族的信息

get 'namespace:表名','rowkey','列族'

image-20221030210307315

scan查询表中所有数据

scan 'namespace:表名'

image-20221030210417431

1.3、删除数据

delete 'namespace:表','rowkey','列族:列名'

image-20221030211204473

image-20221030211220885

删除某个rowkey对应的数据

deleteall 'namespace:表','rowkey'

1.4、HBase的namespace命名空间
  1. HBase的命名空间相当于MySQL中的database
  2. HBase默认有2个命名空间:分别是hbase和default
  3. 其中hbase存放系统表,default是存放用户表

image-20221030212123542

创建指定命名空间的表

create 'testnamespace:test','info','level'

查看指定命名空间的表

list_namespace_tables 'testnamespace'

二、Java代码操作HBase

2.1、pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
​
    <groupId>com.strivelearn</groupId>
    <artifactId>hbase</artifactId>
    <version>1.0-SNAPSHOT</version>
​
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <slf4j.version>1.7.25</slf4j.version>
        <hbase.version>2.2.7</hbase.version>
    </properties>
​
    <dependencies>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>2.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
    </dependencies>
</project>
2.2、log4j.properties
log4j.rootLogger=info,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5p] [%t] %m %n
2.3、获取HBase数据库链接
/**
 * Gets connection.
 *
 * @return the connection
 * @throws IOException the io exception
 */
private static Connection getConnection() throws IOException {
    //获取配置
    Configuration configuration = HBaseConfiguration.create();
    //指定HBase使用的zk地址,多个使用逗号隔开
    configuration.set("hbase.zookeeper.quorum", "192.168.234.100:2181");
    //指定HBase在hdfs上的根目录
    configuration.set("hbase.rootdir", "hdfs://bigdata01:9000/hbase");
    //创建HBase连接,负责对HBase中的数据的一些增删改查(DML操作)
    Connection connection = ConnectionFactory.createConnection(configuration);
    return connection;
}
2.4、往HBase中添加数据
/**
 * Put.
 *
 * @param connection the connection
 * @throws IOException the io exception
 */
private static void put(Connection connection) throws IOException {
    //获取Table,指定要操作的表名,表要提前创建好
    Table student = connection.getTable(TableName.valueOf("student"));
    //指定RowKey,返回put对象
    Put put = new Put(Bytes.toBytes("lisi"));
    //put 'student','lisi','info:age','18'
    put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"), Bytes.toBytes("18"));
    //put 'student','lisi','info:sex','man'
    put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("sex"), Bytes.toBytes("man"));
    //put 'student','lisi','level:class','三年二班'
    put.addColumn(Bytes.toBytes("level"), Bytes.toBytes("class"), Bytes.toBytes("三年二班"));
    //向表中添加数据
    student.put(put);
    student.close();
}
2.5、获取HBase中的最新版本的数据
/**
 * Gets content.
 *
 * @param connection the connection
 * @throws IOException the io exception
 */
private static void getNewVersionValue(Connection connection) throws IOException {
    //获取Table,指定要操作的表名,表需要提前创建好
    Table student = connection.getTable(TableName.valueOf("student"));
    //指定RowKey,返回Get对象
    Get get = new Get(Bytes.toBytes("lisi"));
    //【可选】可以在这里指定要查询指定RowKey数据哪些列族的列
    //如果不指定,默认查询指定RowKey所有列的内容
    //        get.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"));
    //        get.addColumn(Bytes.toBytes("info"), Bytes.toBytes("sex"));
    Result result = student.get(get);
    //1、如果不清楚HBase到底有哪些列族和列,可以使用listCells()获取所有的cell(单元格),cell对应的是某一列的数据
    List<Cell> cells = result.listCells();
    for (Cell cell : cells) {
        //列族
        byte[] familyBytes = CellUtil.cloneFamily(cell);
        //列
        byte[] columnBytes = CellUtil.cloneQualifier(cell);
        //值
        byte[] valueBytes = CellUtil.cloneValue(cell);
        System.out.println("列族:" + new String(familyBytes) + ",列:" + new String(columnBytes) + ",值:" + new String(valueBytes));
    }
    System.out.println("=======");
    //2、如果明确知道HBase中有哪些列,可以使用getValue(family,qualifier)直接获取指定列族中指定的值
    byte[] ageValues = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("age"));
    System.out.println("age列的值:" + new String(ageValues));
}
2.6、获取HBase中多版本的数据
/**
 * Gets multiple version value.
 * 查询多版本的数据
 * 当列的值有多个版本的时候
 * 修改列族info的最大历史版本存储数量
 * alter 'student',{NAME=>'info',VERSIONS=>3}(ps:这边的name一定要大写,versions也要大写)
 * 然后执行下面命令,向列族info中的age列添加几次数据,实现多历史版本数据存储
 * put 'student','lisi','info:age','19'
 * put 'student','lisi','info:age','20'
 *
 * @param connection the connection
 */
private static void getMultipleVersionValue(Connection connection) throws IOException {
    //获取Table,指定要操作的表名,表要提前创建好
    Table student = connection.getTable(TableName.valueOf("student"));
    //指定RowKey,返回Get对象
    Get get = new Get(Bytes.toBytes("lisi"));
    //读取cell中的所有历史版本数据,不设置此配置时默认只读取最新版本的数据
    //可以通过get.readVersions(x)来指定获取多少个历史版本的数据
    get.readAllVersions();
    Result result = student.get(get);
    //获取指定列族中指定列的所有历史版本数据,前提是要设置get.readAllVersion()或者get.readVersions(x)。否则只会获取最新的数据
    List<Cell> columnCells = result.getColumnCells(Bytes.toBytes("info"), Bytes.toBytes("age"));
    for (Cell columnCell : columnCells) {
        byte[] value = CellUtil.cloneValue(columnCell);
        long timestamp = columnCell.getTimestamp();
        System.out.println("值为:" + new String(value) + ",时间戳:" + timestamp);
    }
}
2.7、删除HBase指定列族的数据
/**
 * Delete.
 *
 * @param connection the connection
 * @throws IOException the io exception
 */
public static void delete(Connection connection) throws IOException {
    //获取Table,指定要操作的表名,表要提前创建好
    Table student = connection.getTable(TableName.valueOf("student"));
    //指定RowKey,返回Delete对象
    Delete deleteOperate = new Delete(Bytes.toBytes("lisi"));
    //【可选】可以在这里指定要删除指定RowKey数据哪些列族中的列
    deleteOperate.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"));
    student.delete(deleteOperate);
}

image-20221104221133660

执行删除的代码后

image-20221104221158452

2.8、创建表结构
/**
 * Create table.
 *
 * @param connection the connection
 * @throws IOException the io exception
 */
public static void createTable(Connection connection) throws IOException {
    //获取管理权限,负责对HBase中的表进行操作(DDL操作)
    Admin admin = connection.getAdmin();
​
    //指定列族信息
    ColumnFamilyDescriptor info = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"))
                                                               //指定最多存储多少个历史版本数据
                                                               .setMaxVersions(3)
                                                               .build();
​
    //指定列族信息
    ColumnFamilyDescriptor level = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("level"))
                                                                //指定最多存储多少个历史版本数据
                                                                .setMaxVersions(3)
                                                                .build();
    ArrayList<ColumnFamilyDescriptor> familyDescriptors = new ArrayList<>();
    familyDescriptors.add(info);
    familyDescriptors.add(level);
    //获取TableDescriptor对象
    TableDescriptor test = TableDescriptorBuilder.newBuilder(TableName.valueOf("test")).setColumnFamilies(familyDescriptors).build();
    admin.createTable(test);
    admin.close();
}

image-20221104224025234

2.9、删除表
/**
 * Delete table.
 *
 * @param connection the connection
 * @param tableName  the table name
 * @throws IOException the io exception
 */
public static void deleteTable(Connection connection, String tableName) throws IOException {
    //获取管理权限,负责对HBase中的表进行操作(DDL操作)
    Admin admin = connection.getAdmin();
    //删除表前先禁用表
    admin.disableTable(TableName.valueOf(tableName));
    admin.deleteTable(TableName.valueOf(tableName));
    admin.close();
}
image-20221104224433695