HBase学习

作者: Wizey | 来源:发表于2018-07-05 10:52 被阅读14次

    HBase 中用 put 命令添加数据,但在 HBase 中一次只能为一个表的一行数据的一个列,也就是一个单元格添加一个数据,这点和关系型数据库是不一样的,在关系型数据库中直接是插入整行的数据,所以 HBase 直接用 shell 命令插入数据效率很低,在实际应用中,一般都是利用编程操作 HBase 的。

    1. HBase 操作命令

    • 表列表:

      命令格式:list

    • 创建表:

      命令格式(不指定默认保存的版本数,默认值为 3):create '表名','列族1','列族2'

      命令格式(指定默认保存的版本数):create '表名',{NAME=>'列族1',VERSIONS=>保存的版本数}, {NAME=>'列族2',VERSIONS=>保存的版本数}

    • 查看表描述:

      命令格式:describe '表名'

    • 删除表:

      命令格式(先使该表不可用):disable '表名'

      命令格式(删除表):drop '表名'

    • 添加数据:

      命令格式(列族只有单个列名):put '表名','行号','列族','列值'

      命令格式(列族有多个列名):put '表名','行号','列族:列名','列值'

    • 删除数据:

      命令格式(删除某个单元格数据):delete '表名','行号','列族'

      命令格式(删除某行号数据):deleteall '表名','行号'

    • 修改数据:

      命令格式(HBase中实际上是没有修改数据命令的):put '表名','行号','列族','新的单元格值'

    • 查看数据:

      命令格式(查看某个列族的数据):get '表名','行号',{COLUMN=>'列族',VERSIONS=>查看的版本数}

      命令格式(查看某行号数据):get '表名','行号'

      命令格式(查看整个表的数据):scan '表名'

    2. Java 编程来操作 HBase

    操作 HBase 所用的 jar 包,使用 Maven 导入,引入依赖 hbase-it,pom.xml 文件依赖部分如下:

    说明:我安装的 HBase 是 1.1.0 版本的,所以这里使用的依赖版本也是 1.1.0,请保持 jar 包版本和 HBase 版本一致。

    <dependencies>
        <dependency>
          <groupId>org.apache.hbase</groupId>
          <artifactId>hbase-it</artifactId>
          <version>1.1.0</version>
        </dependency>
      </dependencies>
    

    HBase 的提供的 jar 包只是对 HBase 命令操作的基本封装,为了便于使用,可以在此基础上做进一步的封装来调用。

    下面是 HBase 封装后的工具类 HBaseUtil

    package com.weizhiwen.util;
    import java.io.IOException;
    
    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.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.Table;
    
    public class HBaseUtil {
      public static Configuration configuration;
      public static Connection connection;
      public static Admin admin;
      /**
       * 建表。HBase的表中会有一个系统默认的属性作为主键,
       * 主键无需自行创建,默认为put命令操作中表名后第一个数据,
       * 因此此处无需创建id列
       * @param myTableName 表名
       * @param columnFamily 列族数组
       * @throws IOException 
       */
      @SuppressWarnings("all")
      public static void createTable(String myTableName, String[] columnFamily) throws IOException {
        init();
        TableName tableName = TableName.valueOf(myTableName);
        if(admin.tableExists(tableName)) {
          System.out.println(myTableName+" is exists");
        } else {
          HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
          for(String columnName : columnFamily) {
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(columnName);
            hTableDescriptor.addFamily(hColumnDescriptor);
          }
          admin.createTable(hTableDescriptor);
          System.out.println("create "+myTableName+" success");
        }
        close();
      }
      
      /**
       * 删除指定表
       * @param myTableName 表名
       * @throws IOException
       */
      public static void deleteTable(String myTableName) throws IOException {
        init();
        TableName tableName = TableName.valueOf(myTableName);
        if (admin.tableExists(tableName)) {
            admin.disableTable(tableName); // 先使表无效
            admin.deleteTable(tableName); // 在删除表
        }
        close();
      }
      
      /**
       * 查看已有表
       * @throws IOException
       */
      public static void listTables() throws IOException {
          init();
          HTableDescriptor hTableDescriptors[] = admin.listTables();
          for(HTableDescriptor hTableDescriptor : hTableDescriptors){
              System.out.println(hTableDescriptor.getNameAsString());
          }
          close();
      }
      
      /**
       * 向某一行的某一列插入数据
       * @param myTableName 表名
       * @param rowKey 行键
       * @param colFamily 列族名
       * @param column 列名(如果列族下没有子列名,此参数可为空)
       * @param value 单元格值
       * @throws IOException
       */
      public static void insertRowData(String tableName, String rowKey, String colFamily, String column, String value) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(rowKey.getBytes());
        put.addColumn(colFamily.getBytes(), column.getBytes(), value.getBytes());
        table.put(put);
        table.close();
        close();
      }
      
      /**
       * 删除数据
       * @param tableName 表名
       * @param rowKey 行键
       * @param colFamily 列族名
       * @param col 列名
       * @throws IOException
       */
      public static void deleteRow(String tableName,String rowKey,String colFamily,String col) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(rowKey.getBytes());
        //删除指定列族的所有数据
        //delete.addFamily(colFamily.getBytes());
        //删除指定列的数据
        //delete.addColumn(colFamily.getBytes(), col.getBytes());
    
        table.delete(delete);
        table.close();
        close();
      }
      
      /**
       * 根据行键查询数据
       * @param tableName 表名
       * @param rowKey 行键
       * @param colFamily 列族名
       * @param col 列名
       * @throws IOException
       */
      public static void getRowData(String tableName,String rowKey,String colFamily,String col)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes());
        get.addColumn(colFamily.getBytes(),col.getBytes());
        Result result = table.get(get);
        showCell(result);
        table.close();
        close();
      }
      
      /**
       * 格式化输出
       * @param result
       */
      public static void showCell(Result result){
          Cell[] cells = result.rawCells();
          for(Cell cell:cells){
              System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
              System.out.println("Timetamp:"+cell.getTimestamp()+" ");
              System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
              System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
              System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
          }
      }
      
      
      // 建立连接
      public static void init() {
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
        try {
          connection = ConnectionFactory.createConnection(configuration);
          admin = connection.getAdmin();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      
      // 关闭连接
      public static void close() {
        try {
          if(admin != null) {
            admin.close();
          }
          if(connection != null) {
            connection.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    

    工具类的测试类 HBaseUtilTest

    package com.weizhiwen.test;
    
    import java.io.IOException;
    
    import com.weizhiwen.util.HBaseUtil;
    
    public class HBaseTest {
      public static void main(String[] args) throws IOException {
        // 查看 HBase 数据库中的所有表
        HBaseUtil.listTables();
        // 删除成绩表(HBase 数据库中已有数据表)
        HBaseUtil.deleteTable("chengji");
        // 重新创建成绩表
        HBaseUtil.createTable("chengji", new String[]{"score"});
        // 插入数据
        HBaseUtil.insertRowData("chengji", "zhangsan", "score", "English", "98");
        HBaseUtil.insertRowData("chengji", "zhangsan", "score", "Math", "94");
        HBaseUtil.insertRowData("chengji", "zhangsan", "score", "Computer", "98");
        // 查看单行数据
        HBaseUtil.getRowData("chengji", "zhangsan", "score", "Math");
      }
    }
    

    上面 HBaseUtil 类的封装也只是基本的封装,还可以根据实际使用 HBase 在来进行自己需要的封装,比如单行多列插入,查询整表等等。

    个人 GitHub 地址:https://github.com/weizhiwen,欢迎来访。

    相关文章

      网友评论

        本文标题:HBase学习

        本文链接:https://www.haomeiwen.com/subject/ruoahftx.html