分享

通过Java Api与HBase交互实例

pig2 2014-8-8 19:29:28 发表于 实操演练 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 5 17299


HBase提供了Java Api的访问接口,掌握这个就跟Java应用使用RDBMS时需要JDBC一样重要
问题导读:

1.如何通过API创建表?
2.通过那个API可以遍历Hbase?
3.如何查询某列数据的多个版本?









  1. import java.io.IOException;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.hbase.HBaseConfiguration;
  4. import org.apache.hadoop.hbase.HColumnDescriptor;
  5. import org.apache.hadoop.hbase.HTableDescriptor;
  6. import org.apache.hadoop.hbase.KeyValue;
  7. import org.apache.hadoop.hbase.client.Delete;
  8. import org.apache.hadoop.hbase.client.Get;
  9. import org.apache.hadoop.hbase.client.HBaseAdmin;
  10. import org.apache.hadoop.hbase.client.HTable;
  11. import org.apache.hadoop.hbase.client.HTablePool;
  12. import org.apache.hadoop.hbase.client.Put;
  13. import org.apache.hadoop.hbase.client.Result;
  14. import org.apache.hadoop.hbase.client.ResultScanner;
  15. import org.apache.hadoop.hbase.client.Scan;
  16. import org.apache.hadoop.hbase.util.Bytes;
  17. public class Hbase {
  18.     // 声明静态配置
  19.     static Configuration conf = null;
  20.     static {
  21.         conf = HBaseConfiguration.create();
  22.         conf.set("hbase.zookeeper.quorum", "localhost");
  23.     }
  24.     /*
  25.      * 创建表
  26.      *
  27.      * @tableName 表名
  28.      *
  29.      * @family 列族列表
  30.      */
  31.     public static void creatTable(String tableName, String[] family)
  32.             throws Exception {
  33.         HBaseAdmin admin = new HBaseAdmin(conf);
  34.         HTableDescriptor desc = new HTableDescriptor(tableName);
  35.         for (int i = 0; i < family.length; i++) {
  36.             desc.addFamily(new HColumnDescriptor(family[i]));
  37.         }
  38.         if (admin.tableExists(tableName)) {
  39.             System.out.println("table Exists!");
  40.             System.exit(0);
  41.         } else {
  42.             admin.createTable(desc);
  43.             System.out.println("create table Success!");
  44.         }
  45.     }
  46.     /*
  47.      * 为表添加数据(适合知道有多少列族的固定表)
  48.      *
  49.      * @rowKey rowKey
  50.      *
  51.      * @tableName 表名
  52.      *
  53.      * @column1 第一个列族列表
  54.      *
  55.      * @value1 第一个列的值的列表
  56.      *
  57.      * @column2 第二个列族列表
  58.      *
  59.      * @value2 第二个列的值的列表
  60.      */
  61.     public static void addData(String rowKey, String tableName,
  62.             String[] column1, String[] value1, String[] column2, String[] value2)
  63.             throws IOException {
  64.         Put put = new Put(Bytes.toBytes(rowKey));// 设置rowkey
  65.         HTable table = new HTable(conf, Bytes.toBytes(tableName));// HTabel负责跟记录相关的操作如增删改查等//
  66.                                                                     // 获取表
  67.         HColumnDescriptor[] columnFamilies = table.getTableDescriptor() // 获取所有的列族
  68.                 .getColumnFamilies();
  69.         for (int i = 0; i < columnFamilies.length; i++) {
  70.             String familyName = columnFamilies[i].getNameAsString(); // 获取列族名
  71.             if (familyName.equals("article")) { // article列族put数据
  72.                 for (int j = 0; j < column1.length; j++) {
  73.                     put.add(Bytes.toBytes(familyName),
  74.                             Bytes.toBytes(column1[j]), Bytes.toBytes(value1[j]));
  75.                 }
  76.             }
  77.             if (familyName.equals("author")) { // author列族put数据
  78.                 for (int j = 0; j < column2.length; j++) {
  79.                     put.add(Bytes.toBytes(familyName),
  80.                             Bytes.toBytes(column2[j]), Bytes.toBytes(value2[j]));
  81.                 }
  82.             }
  83.         }
  84.         table.put(put);
  85.         System.out.println("add data Success!");
  86.     }
  87.     /*
  88.      * 根据rwokey查询
  89.      *
  90.      * @rowKey rowKey
  91.      *
  92.      * @tableName 表名
  93.      */
  94.     public static Result getResult(String tableName, String rowKey)
  95.             throws IOException {
  96.         Get get = new Get(Bytes.toBytes(rowKey));
  97.         HTable table = new HTable(conf, Bytes.toBytes(tableName));// 获取表
  98.         Result result = table.get(get);
  99.         for (KeyValue kv : result.list()) {
  100.             System.out.println("family:" + Bytes.toString(kv.getFamily()));
  101.             System.out
  102.                     .println("qualifier:" + Bytes.toString(kv.getQualifier()));
  103.             System.out.println("value:" + Bytes.toString(kv.getValue()));
  104.             System.out.println("Timestamp:" + kv.getTimestamp());
  105.             System.out.println("-------------------------------------------");
  106.         }
  107.         return result;
  108.     }
  109.     /*
  110.      * 遍历查询hbase表
  111.      *
  112.      * @tableName 表名
  113.      */
  114.     public static void getResultScann(String tableName) throws IOException {
  115.         Scan scan = new Scan();
  116.         ResultScanner rs = null;
  117.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  118.         try {
  119.             rs = table.getScanner(scan);
  120.             for (Result r : rs) {
  121.                 for (KeyValue kv : r.list()) {
  122.                     System.out.println("row:" + Bytes.toString(kv.getRow()));
  123.                     System.out.println("family:"
  124.                             + Bytes.toString(kv.getFamily()));
  125.                     System.out.println("qualifier:"
  126.                             + Bytes.toString(kv.getQualifier()));
  127.                     System.out
  128.                             .println("value:" + Bytes.toString(kv.getValue()));
  129.                     System.out.println("timestamp:" + kv.getTimestamp());
  130.                     System.out
  131.                             .println("-------------------------------------------");
  132.                 }
  133.             }
  134.         } finally {
  135.             rs.close();
  136.         }
  137.     }
  138.     /*
  139.      * 遍历查询hbase表
  140.      *
  141.      * @tableName 表名
  142.      */
  143.     public static void getResultScann(String tableName, String start_rowkey,
  144.             String stop_rowkey) throws IOException {
  145.         Scan scan = new Scan();
  146.         scan.setStartRow(Bytes.toBytes(start_rowkey));
  147.         scan.setStopRow(Bytes.toBytes(stop_rowkey));
  148.         ResultScanner rs = null;
  149.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  150.         try {
  151.             rs = table.getScanner(scan);
  152.             for (Result r : rs) {
  153.                 for (KeyValue kv : r.list()) {
  154.                     System.out.println("row:" + Bytes.toString(kv.getRow()));
  155.                     System.out.println("family:"
  156.                             + Bytes.toString(kv.getFamily()));
  157.                     System.out.println("qualifier:"
  158.                             + Bytes.toString(kv.getQualifier()));
  159.                     System.out
  160.                             .println("value:" + Bytes.toString(kv.getValue()));
  161.                     System.out.println("timestamp:" + kv.getTimestamp());
  162.                     System.out
  163.                             .println("-------------------------------------------");
  164.                 }
  165.             }
  166.         } finally {
  167.             rs.close();
  168.         }
  169.     }
  170.     /*
  171.      * 查询表中的某一列
  172.      *
  173.      * @tableName 表名
  174.      *
  175.      * @rowKey rowKey
  176.      */
  177.     public static void getResultByColumn(String tableName, String rowKey,
  178.             String familyName, String columnName) throws IOException {
  179.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  180.         Get get = new Get(Bytes.toBytes(rowKey));
  181.         get.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName)); // 获取指定列族和列修饰符对应的列
  182.         Result result = table.get(get);
  183.         for (KeyValue kv : result.list()) {
  184.             System.out.println("family:" + Bytes.toString(kv.getFamily()));
  185.             System.out
  186.                     .println("qualifier:" + Bytes.toString(kv.getQualifier()));
  187.             System.out.println("value:" + Bytes.toString(kv.getValue()));
  188.             System.out.println("Timestamp:" + kv.getTimestamp());
  189.             System.out.println("-------------------------------------------");
  190.         }
  191.     }
  192.     /*
  193.      * 更新表中的某一列
  194.      *
  195.      * @tableName 表名
  196.      *
  197.      * @rowKey rowKey
  198.      *
  199.      * @familyName 列族名
  200.      *
  201.      * @columnName 列名
  202.      *
  203.      * @value 更新后的值
  204.      */
  205.     public static void updateTable(String tableName, String rowKey,
  206.             String familyName, String columnName, String value)
  207.             throws IOException {
  208.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  209.         Put put = new Put(Bytes.toBytes(rowKey));
  210.         put.add(Bytes.toBytes(familyName), Bytes.toBytes(columnName),
  211.                 Bytes.toBytes(value));
  212.         table.put(put);
  213.         System.out.println("update table Success!");
  214.     }
  215.     /*
  216.      * 查询某列数据的多个版本
  217.      *
  218.      * @tableName 表名
  219.      *
  220.      * @rowKey rowKey
  221.      *
  222.      * @familyName 列族名
  223.      *
  224.      * @columnName 列名
  225.      */
  226.     public static void getResultByVersion(String tableName, String rowKey,
  227.             String familyName, String columnName) throws IOException {
  228.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  229.         Get get = new Get(Bytes.toBytes(rowKey));
  230.         get.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName));
  231.         get.setMaxVersions(5);
  232.         Result result = table.get(get);
  233.         for (KeyValue kv : result.list()) {
  234.             System.out.println("family:" + Bytes.toString(kv.getFamily()));
  235.             System.out
  236.                     .println("qualifier:" + Bytes.toString(kv.getQualifier()));
  237.             System.out.println("value:" + Bytes.toString(kv.getValue()));
  238.             System.out.println("Timestamp:" + kv.getTimestamp());
  239.             System.out.println("-------------------------------------------");
  240.         }
  241.         /*
  242.          * List<?> results = table.get(get).list(); Iterator<?> it =
  243.          * results.iterator(); while (it.hasNext()) {
  244.          * System.out.println(it.next().toString()); }
  245.          */
  246.     }
  247.     /*
  248.      * 删除指定的列
  249.      *
  250.      * @tableName 表名
  251.      *
  252.      * @rowKey rowKey
  253.      *
  254.      * @familyName 列族名
  255.      *
  256.      * @columnName 列名
  257.      */
  258.     public static void deleteColumn(String tableName, String rowKey,
  259.             String falilyName, String columnName) throws IOException {
  260.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  261.         Delete deleteColumn = new Delete(Bytes.toBytes(rowKey));
  262.         deleteColumn.deleteColumns(Bytes.toBytes(falilyName),
  263.                 Bytes.toBytes(columnName));
  264.         table.delete(deleteColumn);
  265.         System.out.println(falilyName + ":" + columnName + "is deleted!");
  266.     }
  267.     /*
  268.      * 删除指定的列
  269.      *
  270.      * @tableName 表名
  271.      *
  272.      * @rowKey rowKey
  273.      */
  274.     public static void deleteAllColumn(String tableName, String rowKey)
  275.             throws IOException {
  276.         HTable table = new HTable(conf, Bytes.toBytes(tableName));
  277.         Delete deleteAll = new Delete(Bytes.toBytes(rowKey));
  278.         table.delete(deleteAll);
  279.         System.out.println("all columns are deleted!");
  280.     }
  281.     /*
  282.      * 删除表
  283.      *
  284.      * @tableName 表名
  285.      */
  286.     public static void deleteTable(String tableName) throws IOException {
  287.         HBaseAdmin admin = new HBaseAdmin(conf);
  288.         admin.disableTable(tableName);
  289.         admin.deleteTable(tableName);
  290.         System.out.println(tableName + "is deleted!");
  291.     }
  292.     public static void main(String[] args) throws Exception {
  293.         // 创建表
  294.         String tableName = "blog2";
  295.         String[] family = { "article", "author" };
  296.         // creatTable(tableName, family);
  297.         // 为表添加数据
  298.         String[] column1 = { "title", "content", "tag" };
  299.         String[] value1 = {
  300.                 "Head First HBase",
  301.                 "HBase is the Hadoop database. Use it when you need random, realtime read/write access to your Big Data.",
  302.                 "Hadoop,HBase,NoSQL" };
  303.         String[] column2 = { "name", "nickname" };
  304.         String[] value2 = { "nicholas", "lee" };
  305.         addData("rowkey1", "blog2", column1, value1, column2, value2);
  306.         addData("rowkey2", "blog2", column1, value1, column2, value2);
  307.         addData("rowkey3", "blog2", column1, value1, column2, value2);
  308.         // 遍历查询
  309.         getResultScann("blog2", "rowkey4", "rowkey5");
  310.         // 根据row key范围遍历查询
  311.         getResultScann("blog2", "rowkey4", "rowkey5");
  312.         // 查询
  313.         getResult("blog2", "rowkey1");
  314.         // 查询某一列的值
  315.         getResultByColumn("blog2", "rowkey1", "author", "name");
  316.         // 更新列
  317.         updateTable("blog2", "rowkey1", "author", "name", "bin");
  318.         // 查询某一列的值
  319.         getResultByColumn("blog2", "rowkey1", "author", "name");
  320.         // 查询某列的多版本
  321.         getResultByVersion("blog2", "rowkey1", "author", "name");
  322.         // 删除一列
  323.         deleteColumn("blog2", "rowkey1", "author", "nickname");
  324.         // 删除所有列
  325.         deleteAllColumn("blog2", "rowkey1");
  326.         // 删除表
  327.         deleteTable("blog2");
  328.     }
  329. }
复制代码



已有(5)人评论

跳转到指定楼层
sunshine_junge 发表于 2014-8-9 10:58:58
好好学习,天天象山,,,,
回复

使用道具 举报

kkl0086 发表于 2014-10-11 14:08:01
回复

使用道具 举报

break-spark 发表于 2014-10-11 17:39:27
学习中,会好好学的
回复

使用道具 举报

wx_CI3ZMaF4 发表于 2016-8-16 20:34:42
运行后发现连接有问题啊!
WARNING: org.apache.hadoop.metrics.jvm.EventCounter is deprecated. Please use org.apache.hadoop.log.metrics.EventCounter in all the log4j.properties files.
16/08/16 20:21:53 ERROR util.Shell: Failed to locate the winutils binary in the hadoop binary path
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.
        at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:355)
        at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:370)
        at org.apache.hadoop.util.Shell.<clinit>(Shell.java:363)
        at org.apache.hadoop.util.StringUtils.<clinit>(StringUtils.java:78)
        at org.apache.hadoop.conf.Configuration.getStrings(Configuration.java:1709)
        at org.apache.hadoop.hbase.zookeeper.ZKConfig.makeZKProps(ZKConfig.java:102)
        at org.apache.hadoop.hbase.zookeeper.ZKConfig.getZKQuorumServersString(ZKConfig.java:249)
        at org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher.<init>(ZooKeeperWatcher.java:113)
        at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.getZooKeeperWatcher(HConnectionManager.java:1002)
        at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.setupZookeeperTrackers(HConnectionManager.java:304)
        at org.apache.hadoop.hbase.client.HConnectionManager$HConnectionImplementation.<init>(HConnectionManager.java:295)
        at org.apache.hadoop.hbase.client.HConnectionManager.getConnection(HConnectionManager.java:157)
        at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:90)
        at cheng.HBase_conn.createTable(HBase_conn.java:62)
        at cheng.HBase_conn.main(HBase_conn.java:25)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)


static Configuration conf = null;
static {
    conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum","172.16.2.196");
}这个地方是不是没有配置对?
回复

使用道具 举报

tttttttttttt 发表于 2016-9-13 17:01:17
very good 1
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条