【大数据】 Hbase入门:Java HBase Api【学习笔记】

导读:本篇文章讲解 【大数据】 Hbase入门:Java HBase Api【学习笔记】,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

4、Java HBase Api

4.1 添加依赖

在 Maven 的 pom.xml 中添加依赖:

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-server</artifactId>
    <version>2.2.6</version>
</dependency>
<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
    <version>2.2.6</version>
</dependency>

这里需要注意的是,客户端版本和 HBase 版本需要保持一致,否则可能会遇到不兼容的问题。

4.2 入门例子

1、创建表

hbase(main):003:0> create 'stu','score'
Created table stu
Took 1.7148 seconds                                                                                                   
=> Hbase::Table - stu

2、编写代码

package com.school.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ExampleForHBase {
    public Configuration conf;
    public Connection conn;
    public Admin admin;

    /**
     * 初始化连接配置
     * */
    @Before
    public void init() throws IOException {
        conf = HBaseConfiguration.create();
        // 设置连接参数:HBase数据库所在的主机IP
        conf.set("hbase.zookeeper.quorum", "hadoop102");
        // 设置连接参数:HBase数据库使用的端口
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conn = ConnectionFactory.createConnection(conf);
        admin = conn.getAdmin();
    }

    /**
     * 关闭连接
     * */
    @After
    public void close() throws IOException {
        if(admin != null){
            admin.close();
        }
        if(conn != null){
            conn.close();
        }
    }

    /**
     * 查看数据
     * */
    @Test
    public void getData() throws IOException {
        String tableName = "";
        String rowKey = "";
        String colFamily = "";
        String col = "";

        Table table = conn.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes(StandardCharsets.UTF_8));
        get.addColumn(colFamily.getBytes(StandardCharsets.UTF_8),col.getBytes(StandardCharsets.UTF_8));
        Result result = table.get(get);
        System.out.println(new String(result.getValue(colFamily.getBytes(StandardCharsets.UTF_8),
                col==null?null:col.getBytes(StandardCharsets.UTF_8))));
    }

    /**
     * 插入数据
     * */
    @Test
    public void insertData() throws IOException {
        String tableName = "stu";
        String rowKey = "zhangsan";
        String colFamily = "score";
        String col = "English";
        String val = "77";

        Table table = conn.getTable(TableName.valueOf(tableName));
        Put put = new Put(rowKey.getBytes(StandardCharsets.UTF_8));
        put.addColumn(colFamily.getBytes(StandardCharsets.UTF_8),
                col.getBytes(StandardCharsets.UTF_8),
                val.getBytes(StandardCharsets.UTF_8));
        table.put(put);
        table.close();
    }
}

4.3 编程学习例子

4.3.1 学习准备

package com.school.hbase;

import org.apache.hadoop.conf.Configuration;
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.After;
import org.junit.Before;

import java.io.IOException;

public class HBaseClient {
    public static Configuration conf;
    public static Connection conn;
    public static Admin admin;

    /**
     * 初始化连接配置
     * */
    public static void init() throws IOException {
        conf = HBaseConfiguration.create();
        // 设置连接参数:HBase数据库所在的主机IP
        conf.set("hbase.zookeeper.quorum", "hadoop102");
        // 设置连接参数:HBase数据库使用的端口
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conn = ConnectionFactory.createConnection(conf);
        admin = conn.getAdmin();
    }

    /**
     * 关闭连接
     * */
    public static void close() throws IOException {
        if(admin != null){
            admin.close();
        }
        if(conn != null){
            conn.close();
        }
    }

   /**
   * 编写例子
   */

    public static void main(String[] args) throws IOException {
        init();
        createTable("stu",new String[]{"score"});
        close();
    }
}

4.3.2 创建表

createTable(String tableName, String[] fields)

​ 创建表,参数tableName为表的名称,字符串数组fields为存储记录各个字段名称的数组。要求当HBase已经存在名为tableName的表的时候,先删除原有的表,然后再创建新的表。

public static void createTable(String tableName, String[] fields) throws IOException {
    TableName table = TableName.valueOf(tableName);

    if(admin.tableExists(table)){
        System.out.println("表已经存在,删除表");
        admin.deleteTable(table);
    }else{
        System.out.println("表不存在,创建表");
        TableDescriptorBuilder tableDescriptor =
            TableDescriptorBuilder.newBuilder(table);
        for(String str:fields){
            ColumnFamilyDescriptor family = ColumnFamilyDescriptorBuilder.
                newBuilder(Bytes.toBytes(str)).build();
            tableDescriptor.setColumnFamily(family);
        }

        admin.createTable(tableDescriptor.build());
    }

}

4.3.3 添加数据

addRecord(String tableName, String row, String[] fields, String[] values)

​ 向表tableName、行row(用S_Name表示)和字符串数组fields指定的单元格中添加对应的数据values。其中,fields中每个元素如果对应的列族下还有相应的列限定符的话,用“columnFamily:column”表示。例如,同时向“Math”、“Computer Science”、“English”三列添加成绩时,字符串数组fields为{“Score:Math”, ”Score:Computer Science”, ”Score:English”},数组values存储这三门课的成绩。

public static void addRecord(String tableName, String row, String[] fields, String[] values) throws IOException {
    Table table = conn.getTable(TableName.valueOf(tableName));

    for (int i = 0;i != fields.length; i++){
        Put put = new Put(row.getBytes());
        String[] cols = fields[i].split(":");
        put.addColumn(cols[0].getBytes(), cols[1].getBytes(), values[i].getBytes());
        table.put(put);
        table.close();
    }
}

4.3.4 浏览表

scanColumn(String tableName, String column)

​ 浏览表tableName某一列的数据,如果某一行记录中该列数据不存在,则返回null。要求当参数column为某一列族名称时,如果底下有若干个列限定符,则要列出每个列限定符代表的列的数据;当参数column为某一列具体名称(例如“Score:Math”)时,只需要列出该列的数据。

public static void scanColumn(String tableName,String column)throws IOException{
    Table table = conn.getTable(TableName.valueOf(tableName));
    Scan scan = new Scan();
    scan.addFamily(Bytes.toBytes(column));
    ResultScanner scanner = table.getScanner(scan);
    for (Result result = scanner.next(); result != null; result = scanner.next()){
        System.out.println(new String(result.getValue(column.getBytes(StandardCharsets.UTF_8),null)));
    }

    table.close();
}
  • 测试
hbase(main):011:0> scan "Student"
ROW                            COLUMN+CELL                                                                  1                             column=S_Age:, timestamp=1648962169913, value=23                            1                             column=S_Name:, timestamp=1648962169865, value=Zhangsan                      1                             column=S_No:, timestamp=1648962169853, value=2015001                        1                             column=S_Sex:, timestamp=1648962169875, value=male                          2                             column=S_Age:, timestamp=1648962199023, value=22                            2                             column=S_Name:, timestamp=1648962199006, value=Mary                          2                             column=S_No:, timestamp=1648962198995, value=2015002                          2                             column=S_Sex:, timestamp=1648962199015, value=female                          3                             column=S_Age:, timestamp=1648962203362, value=24                              3                             column=S_Name:, timestamp=1648962203331, value=Lisi                          3                             column=S_No:, timestamp=1648962203320, value=2015003                          3                             column=S_Sex:, timestamp=1648962203347, value=male                                     
3 row(s)
Took 0.1842 seconds 
public static void main(String[] args) throws IOException {
        init();
//        createTable("stu",new String[]{"score"});
        scanColumn("Student","S_Age");
        close();
    }
23
22
24

4.3.5 修改表

modifyData(String tableName, String row, String column)

​ 修改表tableName,行row(可以用学生姓名S_Name表示),列column指定的单元格的数据。

/**
     *(4)modifyData(String tableName, String row, String column)
     * 	修改表tableName,行row(可以用学生姓名S_Name表示),列column指定的单元格的数据。
     * */
public static void modifyData(String tableName,String row,String column,String val)throws IOException{
    Table table = conn.getTable(TableName.valueOf(tableName));
    Put put = new Put(row.getBytes());
    put.addColumn(row.getBytes(),column.getBytes(),val.getBytes());
    table.put(put);
    table.close();
}
  • 测试
modifyData("Student","S_Name","column:","zs");
  • 修改前
 S_Name                        column=S_Name:column:, timestamp=1648984427305, value=val
  • 修改成功
 S_Name                        column=S_Name:column:, timestamp=1648984427305, value=zs  

4.3.6 删除表

deleteRow(String tableName, String row)

​ 删除表tableName中row指定的行的记录。

public static void deleteRow(String tableName, String row) throws IOException{
    Table table = conn.getTable(TableName.valueOf(tableName));
    Delete delete = new Delete(row.getBytes());
    table.delete(delete);
    table.close();
}
  • 测试
deleteRow("Student","S_Name");

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92646.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!