当前位置:   article > 正文

实验3 熟悉常用的HBase操作_public static void listtables() throws ioexception

public static void listtables() throws ioexception {

一、实验目的

  1. 理解HBase在Hadoop体系结构中的角色;
  2. 熟练使用HBase操作常用的shell命令;
  3. 熟悉HBase操作常用的Java API;

二、实验平台

  1. 操作系统:Linux;
  2. Hadoop版本:3.1.3;
  3. HBase版本:2.2.2;
  4. JDK版本:1.8;
  5. Java IDE:Eclipse。

三、实验步骤

(一)编程实现以下指定功能,并利用Hadoop提供的HBase Shell命令完成相同任务; 

  1. 列出HBase所有的表的相关新信息,例如表名;
    1. //列出HBase所有的表的相关信息,例如表名、创建时间等
    2. public static void listTables() throws IOException {
    3. init();//建立连接
    4. List<TableDescriptor> tableDescriptors = admin.listTableDescriptors();
    5. for (TableDescriptor tableDescriptor : tableDescriptors) {
    6. TableName tableName = tableDescriptor.getTableName();
    7. System.out.println("Table:"+tableName);
    8. }
    9. close();//关闭连接
    10. }
  2. 在终端打印出指定的表的所有记录数据
    1. //在终端打印出指定的表的所有记录数据
    2. public static void getData(String tableName) throws IOException {
    3. init();
    4. Table table = connection.getTable(TableName.valueOf(tableName));
    5. Scan scan = new Scan();
    6. ResultScanner scanner = table.getScanner(scan);//获取行的遍历器
    7. for (Result result:scanner) {
    8. printRecoder(result);
    9. }
    10. close();
    11. }
    12. //打印一条记录的详情
    13. private static void printRecoder(Result result) {
    14. // TODO Auto-generated method stub
    15. for(Cell cell:result.rawCells()) {
    16. String str1 = Bytes.toString(cell.getRowArray(),cell.getRowOffset(),cell.getRowLength());
    17. System.out.println("行键:"+ str1);
    18. String str2 = Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength());
    19. System.out.println("列簇:" + str2);
    20. String str3 = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
    21. System.out.println("列:" + str3);
    22. String str4 = Bytes.toString(cell.getValueArray(),cell.getValueOffset(),cell.getValueLength());
    23. System.out.println("值:" + str4);
    24. System.out.println("时间戳:" + cell.getTimestamp());
    25. }
    26. }

  3. 向已经创建好的表添加和删除指定的列簇或列
    1. //向已经创建好的表添加和删除指定的列簇或列
    2. //向表添加数据
    3. public static void insterRow(String tableName,String rowKey,String colFamily,String col,String val) throws IOException {
    4. init();
    5. Table table = connection.getTable(TableName.valueOf(tableName));
    6. Put put = new Put(rowKey.getBytes());
    7. put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
    8. table.put(put);
    9. table.close();
    10. close();
    11. }
    12. //删除数据
    13. public static void deleRow(String tableName,String rowKey,String colFamily,String col) throws IOException {
    14. init();
    15. Table table = connection.getTable(TableName.valueOf(tableName));
    16. Delete delete = new Delete(rowKey.getBytes());
    17. //删除指定列簇
    18. delete.addFamily(Bytes.toBytes(colFamily));
    19. //删除指定列
    20. delete.addColumn(Bytes.toBytes(colFamily),Bytes.toBytes(col));
    21. table.delete(delete);
    22. table.close();
    23. close();
    24. }

  4. 清空指定的表的所有记录数据
    1. //清空指定的表的所有记录数据
    2. public static void clearRows(String tableName) throws IOException {
    3. init();
    4. TableName tablename = TableName.valueOf(tableName);
    5. admin.disableTable(tablename);
    6. System.out.println("disable...delete...");
    7. admin.deleteTable(tablename);
    8. System.out.println("delete...over...create");
    9. TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tablename);
    10. ColumnFamilyDescriptor colFamilyDes=ColumnFamilyDescriptorBuilder.newBuilder(" ".getBytes()).build();
    11. tableDescriptor.setColumnFamily(colFamilyDes).build();
    12. admin.createTable(tableDescriptor.build());
    13. close();
    14. }

  5. 统计表的行数
    1. //统计表的行数
    2. public static void countRows(String tableName) throws IOException {
    3. init();
    4. Table table = connection.getTable(TableName.valueOf(tableName));
    5. Scan scan = new Scan();
    6. ResultScanner scanner = table.getScanner(scan);
    7. int num = 0;
    8. for (Result result = scanner.next();result!=null;result=scanner.next()) {
    9. num++;
    10. }
    11. System.out.println("行数:" + num);
    12. scanner.close();
    13. close();
    14. }

    以上的全部代码:

    1. import java.io.IOException;
    2. import java.util.List;
    3. import org.apache.hadoop.conf.Configuration;
    4. import org.apache.hadoop.hbase.client.*;
    5. import org.apache.hadoop.hbase.util.Bytes;
    6. import org.apache.hadoop.hbase.*;
    7. public class Test {
    8. public static Configuration configuration;
    9. public static Connection connection;
    10. public static Admin admin;
    11. //建立连接
    12. public static void init() {
    13. configuration = HBaseConfiguration.create();
    14. configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
    15. try {
    16. connection = ConnectionFactory.createConnection(configuration);
    17. admin = connection.getAdmin();
    18. } catch (IOException e) {
    19. // TODO: handle exception
    20. e.printStackTrace();
    21. }
    22. }
    23. //关闭连接
    24. public static void close() {
    25. try {
    26. if (admin != null) {
    27. admin.close();
    28. }
    29. if (null != connection) {
    30. connection.close();
    31. }
    32. } catch (IOException e) {
    33. // TODO: handle exception
    34. e.printStackTrace();
    35. }
    36. }
    37. //列出HBase所有的表的相关信息,例如表名、创建时间等
    38. public static void listTables() throws IOException {
    39. init();//建立连接
    40. List<TableDescriptor> tableDescriptors = admin.listTableDescriptors();
    41. for (TableDescriptor tableDescriptor : tableDescriptors) {
    42. TableName tableName = tableDescriptor.getTableName();
    43. System.out.println("Table:"+tableName);
    44. }
    45. close();//关闭连接
    46. }
    47. //在终端打印出指定的表的所有记录数据
    48. public static void getData(String tableName) throws IOException {
    49. init();
    50. Table table = connection.getTable(TableName.valueOf(tableName));
    51. Scan scan = new Scan();
    52. ResultScanner scanner = table.getScanner(scan);//获取行的遍历器
    53. for (Result result:scanner) {
    54. printRecoder(result);
    55. }
    56. close();
    57. }
    58. //打印一条记录的详情
    59. private static void printRecoder(Result result) {
    60. // TODO Auto-generated method stub
    61. for(Cell cell:result.rawCells()) {
    62. String str1 = Bytes.toString(cell.getRowArray(),cell.getRowOffset(),cell.getRowLength());
    63. System.out.println("行键:"+ str1);
    64. String str2 = Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength());
    65. System.out.println("列簇:" + str2);
    66. String str3 = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
    67. System.out.println("列:" + str3);
    68. String str4 = Bytes.toString(cell.getValueArray(),cell.getValueOffset(),cell.getValueLength());
    69. System.out.println("值:" + str4);
    70. System.out.println("时间戳:" + cell.getTimestamp());
    71. }
    72. }
    73. //向已经创建好的表添加和删除指定的列簇或列
    74. //向表添加数据
    75. public static void insterRow(String tableName,String rowKey,String colFamily,String col,String val) throws IOException {
    76. init();
    77. Table table = connection.getTable(TableName.valueOf(tableName));
    78. Put put = new Put(rowKey.getBytes());
    79. put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
    80. table.put(put);
    81. table.close();
    82. close();
    83. }
    84. //删除数据
    85. public static void deleRow(String tableName,String rowKey,String colFamily,String col) throws IOException {
    86. init();
    87. Table table = connection.getTable(TableName.valueOf(tableName));
    88. Delete delete = new Delete(rowKey.getBytes());
    89. //删除指定列簇
    90. delete.addFamily(Bytes.toBytes(colFamily));
    91. //删除指定列
    92. delete.addColumn(Bytes.toBytes(colFamily),Bytes.toBytes(col));
    93. table.delete(delete);
    94. table.close();
    95. close();
    96. }
    97. //清空指定的表的所有记录数据
    98. public static void clearRows(String tableName) throws IOException {
    99. init();
    100. TableName tablename = TableName.valueOf(tableName);
    101. admin.disableTable(tablename);
    102. System.out.println("disable...delete...");
    103. admin.deleteTable(tablename);
    104. System.out.println("delete...over...create");
    105. TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tablename);
    106. ColumnFamilyDescriptor colFamilyDes=ColumnFamilyDescriptorBuilder.newBuilder(" ".getBytes()).build();
    107. tableDescriptor.setColumnFamily(colFamilyDes).build();
    108. admin.createTable(tableDescriptor.build());
    109. close();
    110. }
    111. //统计表的行数
    112. public static void countRows(String tableName) throws IOException {
    113. init();
    114. Table table = connection.getTable(TableName.valueOf(tableName));
    115. Scan scan = new Scan();
    116. ResultScanner scanner = table.getScanner(scan);
    117. int num = 0;
    118. for (Result result = scanner.next();result!=null;result=scanner.next()) {
    119. num++;
    120. }
    121. System.out.println("行数:" + num);
    122. scanner.close();
    123. close();
    124. }
    125. public static void main(String[] args) throws IOException {
    126. // TODO Auto-generated method stub
    127. // listTables();
    128. // getData("teacher");
    129. // getData("student");
    130. // deleRow("s1", "lisi", "score", "English");
    131. // clearRows("s1");
    132. // countRows("s2");
    133. insterRow("s2", "xiaohong", "score", "Computer", "60");
    134. }
    135. }

(二)HBase数据库操作

1. 现有以下关系型数据库中的表和数据(见表14-3到表14-5),要求将其转换为适合于HBase存储的表并插入数据:

表14-3 学生表(Student)

学号(S_No)

姓名(S_Name)

性别(S_Sex)

年龄(S_Age)

2015001

Zhangsan

male

23

2015002

Mary

female

22

2015003

Lisi

male

24

表14-4 课程表(Course)

课程号(C_No)

课程名(C_Name)

学分(C_Credit)

123001

Math

2.0

123002

Computer Science

5.0

123003

English

3.

表14-5 选课表(SC)

学号(SC_Sno)

课程号(SC_Cno)

成绩(SC_Score)

2015001

123001

86

2015001

123003

69

2015002

123002

77

2015002

123003

99

2015003

123001

98

2015003

123002

95

创建表:

 添加数据:

 

 

2. 请编程实现以下功能:

(1)createTable(String tableName, String[] fields)

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

(2)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存储这三门课的成绩。

(3)scanColumn(String tableName, String column)

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

(4)modifyData(String tableName, String row, String column)

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

(5)deleteRow(String tableName, String row)

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

  1. import org.apache.hadoop.conf.Configuration;
  2. import org.apache.hadoop.hbase.*;
  3. import org.apache.hadoop.hbase.client.*;
  4. import org.apache.hadoop.hbase.util.Bytes;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. public class Test2 {
  9. public static Configuration configuration;
  10. public static Connection connection;
  11. public static Admin admin;
  12. //建立连接
  13. public static void init(){
  14. configuration = HBaseConfiguration.create();
  15. configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
  16. try{
  17. connection = ConnectionFactory.createConnection(configuration);
  18. admin = connection.getAdmin();
  19. }catch (IOException e){
  20. e.printStackTrace();
  21. }
  22. }
  23. //关闭连接
  24. public static void close(){
  25. try{
  26. if(admin != null){
  27. admin.close();
  28. }
  29. if(null != connection){
  30. connection.close();
  31. }
  32. }catch (IOException e){
  33. e.printStackTrace();
  34. }
  35. }
  36. /*createTable(String tableName, String[] fields)
  37. 创建表,参数tableName为表的名称,字符串数组fields为存储记录各个域名称的数组。
  38. 要求当HBase已经存在名为tableName的表的时候,先删除原有的表,然后再创建新的表。
  39. */
  40. public static void createTable(String tableName,String[] fields) throws IOException {
  41. init();
  42. TableName tablename = TableName.valueOf(tableName);
  43. if(admin.tableExists(tablename)){
  44. System.out.println("table is exists!");
  45. admin.disableTable(tablename);
  46. admin.deleteTable(tablename);//删除原来的表
  47. System.out.println("删除成功!");
  48. }
  49. System.out.println("开始创建表...");
  50. List<ColumnFamilyDescriptor> colFamilyList=new ArrayList<>();
  51. TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tablename);
  52. for(String str:fields) {
  53. ColumnFamilyDescriptor colFamilyDes=ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(str)).build();
  54. colFamilyList.add(colFamilyDes);
  55. }
  56. TableDescriptor tableDes=tableDescriptor.setColumnFamilies(colFamilyList).build();
  57. admin.createTable(tableDes);
  58. System.out.println(tableName+"创建成功!");
  59. close();
  60. }
  61. /*addRecord(String tableName, String row, String[] fields, String[] values)
  62. 向表tableName、行row(用S_Name表示)和字符串数组files指定的单元格中添加对应的数据values。
  63. 其中fields中每个元素如果对应的列族下还有相应的列限定符的话,用“columnFamily:column”表示。
  64. 例如,同时向“Math”、“Computer Science”、“English”三列添加成绩时,字符串数组
  65. fields为{“Score:Math”,”Score:Computer Science”,”Score:English”},数组values存储这三门课的成绩。
  66. */
  67. public static void addRecord(String tableName,String row,String[] fields,String[] values) throws IOException {
  68. init();
  69. Table table = connection.getTable(TableName.valueOf(tableName));
  70. System.out.println("准备添加数据...");
  71. for(int i = 0;i != fields.length;i++){
  72. Put put = new Put(row.getBytes());
  73. String[] cols = fields[i].split(":");
  74. put.addColumn(cols[0].getBytes(),cols[1].getBytes(), values[i].getBytes());
  75. System.out.println(i+"put..."+i);
  76. table.put(put);
  77. System.out.println(i+"...ok");
  78. }
  79. table.close();
  80. close();
  81. }
  82. /*(3)scanColumn(String tableName, String column)
  83. 浏览表tableName某一列的数据,如果某一行记录中该列数据不存在,则返回null。
  84. 要求当参数column为某一列族名称时,如果底下有若干个列限定符,则要列出每个列限定符代表的列的数据;
  85. 当参数column为某一列具体名称(例如“Score:Math”)时,只需要列出该列的数据。
  86. */
  87. public static void scanColumn(String tableName,String column)throws IOException{
  88. init();
  89. Table table = connection.getTable(TableName.valueOf(tableName));
  90. Scan scan = new Scan();
  91. scan.addFamily(Bytes.toBytes(column));
  92. ResultScanner scanner = table.getScanner(scan);
  93. for (Result result = scanner.next(); result != null; result = scanner.next()){
  94. showCell(result);
  95. }
  96. table.close();
  97. close();
  98. }
  99. //格式化输出
  100. public static void showCell(Result result){
  101. Cell[] cells = result.rawCells();
  102. for(Cell cell:cells){
  103. System.out.println("RowName:"+new String(Bytes.toString(cell.getRowArray(),cell.getRowOffset(), cell.getRowLength()))+" ");
  104. System.out.println("Timetamp:"+cell.getTimestamp()+" ");
  105. System.out.println("column Family:"+new String(Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(), cell.getFamilyLength()))+" ");
  106. System.out.println("row Name:"+new String(Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(), cell.getQualifierLength()))+" ");
  107. System.out.println("value:"+new String(Bytes.toString(cell.getValueArray(),cell.getValueOffset(), cell.getValueLength()))+" ");
  108. }
  109. }
  110. /*modifyData(String tableName, String row, String column)
  111. 修改表tableName,行row(可以用学生姓名S_Name表示),列column指定的单元格的数据。*/
  112. public static void modifyData(String tableName,String row,String column,String val)throws IOException{
  113. init();
  114. Table table = connection.getTable(TableName.valueOf(tableName));
  115. Put put = new Put(row.getBytes());
  116. String[] col = column.split(":");
  117. put.addColumn(col[0].getBytes(),col[1].getBytes(),val.getBytes());
  118. table.put(put);
  119. table.close();
  120. close();
  121. }
  122. /*(5)deleteRow(String tableName, String row)
  123. 删除表tableName中row指定的行的记录。*/
  124. public static void deleteRow(String tableName,String row)throws IOException{
  125. init();
  126. Table table = connection.getTable(TableName.valueOf(tableName));
  127. Delete delete = new Delete(row.getBytes());
  128. table.delete(delete);
  129. table.close();
  130. close();
  131. }
  132. public static void main(String[] args)throws IOException{
  133. // scanColumn("s1","score");
  134. // String[] fields = {"score"};
  135. // createTable("s1",fields);
  136. String tableName = "s1";
  137. String row = "001";
  138. // String[] fields = {"score:Math", "score:Computer Science", "score:English"};
  139. // String[] values = {"100","80","60"};
  140. // addRecord(tableName,row,fields,values);
  141. // scanColumn(tableName,"score");
  142. // String column = "score:English";
  143. // String val = "70";
  144. // modifyData(tableName,row, column, val);
  145. deleteRow(tableName,row);
  146. }
  147. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/736265
推荐阅读
相关标签
  

闽ICP备14008679号