JAVA操作Hbase管理类HbaseManage基本详细操作

来源:互联网 发布:书法集字软件 编辑:程序博客网 时间:2024/06/10 17:44
  1. package hbase;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.List;  
  5. import org.apache.hadoop.conf.Configuration;  
  6. import org.apache.hadoop.hbase.Cell;  
  7. import org.apache.hadoop.hbase.CellUtil;  
  8. import org.apache.hadoop.hbase.HBaseConfiguration;  
  9. import org.apache.hadoop.hbase.TableName;  
  10. import org.apache.hadoop.hbase.client.Admin;  
  11. import org.apache.hadoop.hbase.client.Connection;  
  12. import org.apache.hadoop.hbase.client.ConnectionFactory;  
  13. import org.apache.hadoop.hbase.client.Delete;  
  14. import org.apache.hadoop.hbase.client.Get;  
  15. import org.apache.hadoop.hbase.client.Put;  
  16. import org.apache.hadoop.hbase.client.Result;  
  17. import org.apache.hadoop.hbase.client.ResultScanner;  
  18. import org.apache.hadoop.hbase.client.Scan;  
  19. import org.apache.hadoop.hbase.client.Table;  
  20. import org.apache.hadoop.hbase.filter.BinaryComparator;  
  21. import org.apache.hadoop.hbase.filter.ColumnPrefixFilter;  
  22. import org.apache.hadoop.hbase.filter.ColumnRangeFilter;  
  23. import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;  
  24. import org.apache.hadoop.hbase.filter.FamilyFilter;  
  25. import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;  
  26. import org.apache.hadoop.hbase.filter.MultipleColumnPrefixFilter;  
  27. import org.apache.hadoop.hbase.filter.PageFilter;  
  28. import org.apache.hadoop.hbase.filter.PrefixFilter;  
  29. import org.apache.hadoop.hbase.filter.QualifierFilter;  
  30. import org.apache.hadoop.hbase.filter.RowFilter;  
  31. import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;  
  32. import org.apache.hadoop.hbase.filter.SkipFilter;  
  33. import org.apache.hadoop.hbase.filter.SubstringComparator;  
  34. import org.apache.hadoop.hbase.filter.ValueFilter;  
  35. import org.apache.hadoop.hbase.util.Bytes;  
  36. /** 
  37.  * @author Administrator 
  38.  * HBase的查询实现只提供两种方式: 
  39.     1、按指定RowKey获取唯一一条记录,get方法(org.apache.hadoop.hbase.client.Get) 
  40.     2、按指定的条件获取一批记录,scan方法(org.apache.Hadoop.Hbase.client.Scan) 
  41.  */  
  42. public class HbaseManage {  
  43.     private static Configuration conf = null;  
  44.   
  45.     private static Connection connection = null;  
  46.     // 初始化hbase  
  47.     static {  
  48.         // windows环境下 解决hadoop调用本地库问题  
  49.         System.setProperty("hadoop.home.dir",  
  50.                 "C:/Users/Administrator/Downloads/hadoop-common-2.2.0-bin-master");  
  51.         conf = HBaseConfiguration.create();// 使用默认的classpath下的hbase-site.xml配置  
  52.         if (connection == null) {  
  53.             try {  
  54.                 connection = ConnectionFactory.createConnection(conf);  
  55.             } catch (IOException e) {  
  56.                 e.printStackTrace();  
  57.             }  
  58.         }  
  59.     }  
  60.   
  61.     // 判断表是否存在  
  62.     private static boolean isExistTable(String tableName) throws IOException {  
  63.         boolean exist = false;  
  64. //       HBaseAdmin hAdmin = new HBaseAdmin(conf);  
  65.         Admin admin = connection.getAdmin();  
  66. //       exist = hAdmin.tableExists(tableName);  
  67.          exist = admin.tableExists(TableName.valueOf(tableName));  
  68.         return exist;  
  69.     }  
  70.   
  71.     /** 
  72.      *  插入数据 
  73.      * @param tableName 
  74.      * @param rowkey 
  75.      * @param columnFamily 
  76.      * @param column 
  77.      * @param value 
  78.      * @throws IOException 
  79.      */  
  80.     public static void putData(String tableName, String rowkey,  
  81.             String columnFamily, String column, String value)  
  82.             throws IOException {  
  83. //       HTable table = new HTable(conf, tableName);  
  84.          Table table = connection.getTable(TableName.valueOf(tableName));  
  85.          Put put = new Put(Bytes.toBytes(rowkey));  
  86. //       put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column),  
  87. //       Bytes.toBytes(column));  
  88.          put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column),  
  89.                     Bytes.toBytes(value));  
  90.            
  91.          table.put(put);  
  92. //       table.put(List<Put>);  
  93.     }  
  94.       
  95.       
  96.     /** 
  97.      * 获取指定行的所有数据 
  98.      * @param tableName 表名 
  99.      * @param row 行键key 
  100.      * @param columnFamily 列族 
  101.      * @param column 列名 
  102.      * @throws IOException  
  103.      */  
  104.     public static void getData(String tableName,String rowKey,String columnFamily,String column) throws IOException{  
  105.     //   HTable table = new HTable(conf, tableName);  写法已过时  
  106.          Table table = connection.getTable(TableName.valueOf(tableName));  
  107.         // Scan scan = new Scan();  
  108.         // ResultScanner  result = table.getScanner(scan);  
  109.          Get get = new Get(Bytes.toBytes(rowKey));  
  110.          Result result = table.get(get);  
  111.          byte[] rb = result.getValue(Bytes.toBytes(columnFamily), Bytes.toBytes(column));  
  112.          String value = new String(rb,"UTF-8");  
  113.          System.out.println(value);  
  114.     }  
  115.       
  116.       
  117.       
  118.     /** 
  119.      * 获取指定表的所有数据 
  120.      * @param tableName 表名 
  121.      * @throws IOException  
  122.      */  
  123.     public static void scanTable(String tableName) throws IOException{  
  124. //       HTable table = new HTable(hbaseConfiguration, tableName);  
  125.          Table table = connection.getTable(TableName.valueOf(tableName));  
  126.          Scan scan = new Scan();  
  127.          ResultScanner resultScanner = table.getScanner(scan);  
  128.          for (Result result : resultScanner) {  
  129.              List<Cell> cells= result.listCells();  
  130.              for (Cell cell : cells) {  
  131.                  byte[] rb = cell.getValueArray();  
  132.                  String row = Bytes.toString(result.getRow());  
  133.                  String family = Bytes.toString(CellUtil.cloneFamily(cell));  
  134.                  String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));  
  135.                  String value = Bytes.toString(CellUtil.cloneValue(cell));  
  136.                  System.out.println("[row:"+row+"],[family:"+family+"],[qualifier:"+qualifier+"],[value:"+value+"]");  
  137.              }  
  138.         }  
  139.     }  
  140.       
  141.       
  142.      /** 
  143.       * 通过rowkey查找数据  
  144.       * @param tableName 
  145.       * @param rowKey 
  146.       * @throws IOException 
  147.       */  
  148.     public static void getDataByRow (String tableName, String rowKey) throws IOException{    
  149. //        HTable table = new HTable(conf, tableName);    
  150.         Table table = connection.getTable(TableName.valueOf(tableName));  
  151.         Get get = new Get(rowKey.getBytes());    
  152.         Result rs = table.get(get);    
  153.         for(Cell cell : rs.listCells()){    
  154.             System.out.print(Bytes.toString(CellUtil.cloneRow(cell))+"  ");    
  155.             System.out.print(Bytes.toString(CellUtil.cloneFamily(cell))+"   ");    
  156.             System.out.print(Bytes.toString(CellUtil.cloneQualifier(cell))+"    ");    
  157.             System.out.print(Bytes.toString(CellUtil.cloneValue(cell))+"    ");    
  158.             System.out.println(cell.getTimestamp());   
  159.             String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));  
  160.             System.out.println(Bytes.toString(cell.getQualifierArray()));  
  161.         }    
  162.     }    
  163.       
  164.   
  165.     /** 
  166.      * 通过列簇获取 下面所有的列的数据 
  167.      * @param tableName 
  168.      * @param family 
  169.      * @throws IOException 
  170.      */  
  171.     public static void getDataByFamilyColumn(String tableName,String family,String column) throws IOException{  
  172.          Table table = connection.getTable(TableName.valueOf(tableName));  
  173.          Scan scan = new Scan();  
  174.          if (!column.isEmpty()) {  
  175.             scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(column));  
  176.         }else {  
  177.             scan.addFamily(Bytes.toBytes(family));  
  178.         }  
  179.          ResultScanner resultScanner = table.getScanner(scan);  
  180.          int count = 0;  
  181.          for (Result result : resultScanner) {  
  182.              List<Cell> cells= result.listCells();  
  183.              for (Cell cell : cells) {  
  184.                  byte[] rb = cell.getValueArray();  
  185.                  String row = Bytes.toString(result.getRow());  
  186.                  String family1 = Bytes.toString(CellUtil.cloneFamily(cell));  
  187.                  String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));  
  188.                  String value = Bytes.toString(CellUtil.cloneValue(cell));  
  189.                  System.out.println("[row:"+row+"],[family:"+family1+"],[qualifier:"+qualifier+"]"  
  190.                         + ",[value:"+value+"],[time:"+cell.getTimestamp()+"]");  
  191.             }  
  192.              count++;  
  193.         }  
  194.          System.out.println("count ===== "+count);  
  195.     }  
  196.       
  197.       
  198.     public static void deleteByRow(String tableName,String row) throws IOException{  
  199.         Table table = connection.getTable(TableName.valueOf("user"));  
  200.         Delete del = new Delete(Bytes.toBytes("zhangsan"));  
  201.         table.delete(del);  
  202.     }  
  203.       
  204.       
  205.     public static void getDataByRowFilter(String tableName,String prefixRow) throws IOException{  
  206.          Table table = connection.getTable(TableName.valueOf(tableName));  
  207.          Scan scan = new Scan();  
  208.          scan.setMaxVersions();  
  209.          PrefixFilter pf = new PrefixFilter(Bytes.toBytes(prefixRow));  
  210.          scan.setFilter(pf);  
  211.          ResultScanner resultScanner = table.getScanner(scan);  
  212.            
  213.          for (Result result : resultScanner) {  
  214.              List<Cell> cells= result.listCells();  
  215.              for (Cell cell : cells) {  
  216.                  byte[] rb = cell.getValueArray();  
  217.                  String row = Bytes.toString(result.getRow());  
  218.                  String family1 = Bytes.toString(CellUtil.cloneFamily(cell));  
  219.                  String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));  
  220.                  String value = Bytes.toString(CellUtil.cloneValue(cell));  
  221.                  System.out.println("[row:"+row+"],[family:"+family1+"],[qualifier:"+qualifier+"]"  
  222.                         + ",[value:"+value+"],[time:"+cell.getTimestamp()+"]");  
  223.             }  
  224.         }  
  225.     }  
  226.       
  227.       
  228.     public static void getDataBySingleCol(String tableName,String family,String column,String cvalue) throws IOException{  
  229.          Table table = connection.getTable(TableName.valueOf(tableName));  
  230.          Scan scan = new Scan();  
  231. //         scan.setMaxVersions();  
  232.          SingleColumnValueFilter scvf= new SingleColumnValueFilter(Bytes.toBytes(family), Bytes.toBytes(column),   
  233.                  CompareOp.EQUAL,Bytes.toBytes(cvalue));  
  234.          scvf.setFilterIfMissing(true); //默认为false, 没有此列的数据也会返回 ,为true则只返回name=lisi的数据  
  235.          scan.setFilter(scvf);  
  236.          ResultScanner resultScanner = table.getScanner(scan);  
  237.          for (Result result : resultScanner) {  
  238.              List<Cell> cells= result.listCells();      
  239.              for (Cell cell : cells) {  
  240.                  byte[] rb = cell.getValueArray();  
  241.                  String row = Bytes.toString(result.getRow());  
  242.                  String family1 = Bytes.toString(CellUtil.cloneFamily(cell));  
  243.                  String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));  
  244.                  String value = Bytes.toString(CellUtil.cloneValue(cell));  
  245.                  System.out.println("[row:"+row+"],[family:"+family1+"],[qualifier:"+qualifier+"]"  
  246.                         + ",[value:"+value+"],[time:"+cell.getTimestamp()+"]");  
  247.             }  
  248.         }  
  249.     }  
  250.       
  251.       
  252.       
  253.     public static ResultScanner getDataSingleColumnValueFilter(String tableName,String family,String column,String value) throws IOException{  
  254.         Table table = connection.getTable(TableName.valueOf(tableName));  
  255.         SingleColumnValueFilter scvf= new SingleColumnValueFilter(Bytes.toBytes(family), Bytes.toBytes(column),   
  256.              CompareOp.EQUAL,Bytes.toBytes(value));  
  257.           
  258. //        SingleColumnValueFilter scvf1= new SingleColumnValueFilter(Bytes.toBytes("account"), Bytes.toBytes("name"),   
  259. //                   CompareOp.EQUAL,new BinaryComparator(Bytes.toBytes("zhangsan")));  //匹配完整字节数组  
  260. //                                   new BinaryPrefixComparator(value) //匹配字节数组前缀  
  261. //                                   new RegexStringComparator(expr) // 正则表达式匹配  
  262. //                                   new SubstringComparator(substr)// 子字符串匹配   
  263.           
  264.         scvf.setFilterIfMissing(true); //默认为false, 没有此列的数据也会返回 ,为true则只返回name=lisi的数据  
  265.         Scan scan = new Scan();  
  266.         scan.setFilter(scvf);  
  267.         ResultScanner resultScanner = table.getScanner(scan);  
  268.         return resultScanner;  
  269.     }  
  270.       
  271.       
  272.     public static ResultScanner getDataFamilyFilter(String tableName,String family) throws IOException{  
  273.         Table table = connection.getTable(TableName.valueOf(tableName));  
  274.         FamilyFilter ff = new FamilyFilter(CompareOp.EQUAL ,   
  275.                 new BinaryComparator(Bytes.toBytes(family)));   //表中不存在account列族,过滤结果为空  
  276. //       new BinaryPrefixComparator(value) //匹配字节数组前缀  
  277. //       new RegexStringComparator(expr) // 正则表达式匹配  
  278. //       new SubstringComparator(substr)// 子字符串匹配   
  279.         Scan scan = new Scan();  
  280.         // 通过scan.addFamily(family)  也可以实现此操作  
  281.         scan.setFilter(ff);  
  282.         ResultScanner resultScanner = table.getScanner(scan);  
  283.         return resultScanner;  
  284.     }  
  285.     public static ResultScanner getDataQualifierFilter(String tableName,String qualifier) throws IOException{  
  286.         Table table = connection.getTable(TableName.valueOf(tableName));  
  287.         QualifierFilter ff = new QualifierFilter(  
  288.                 CompareOp.EQUAL , new BinaryComparator(Bytes.toBytes(qualifier)));  
  289. //       new BinaryPrefixComparator(value) //匹配字节数组前缀  
  290. //       new RegexStringComparator(expr) // 正则表达式匹配  
  291. //       new SubstringComparator(substr)// 子字符串匹配   
  292.         Scan scan = new Scan();  
  293.         // 通过scan.addFamily(family)  也可以实现此操作  
  294.         scan.setFilter(ff);  
  295.         ResultScanner resultScanner = table.getScanner(scan);  
  296.         return resultScanner;  
  297.     }  
  298.       
  299.     public static ResultScanner getDataColumnPrefixFilter(String tableName,String qualifier) throws IOException{  
  300.         Table table = connection.getTable(TableName.valueOf(tableName));  
  301.          ColumnPrefixFilter ff = new ColumnPrefixFilter(Bytes.toBytes(qualifier));  
  302.         Scan scan = new Scan();  
  303.         // 通过QualifierFilter的 newBinaryPrefixComparator也可以实现  
  304.         scan.setFilter(ff);  
  305.         ResultScanner resultScanner = table.getScanner(scan);  
  306.         return resultScanner;  
  307.     }  
  308.   /** 
  309.    * 返回 多列内容, 以 cols里内的 byte[]为前缀   
  310.    * @param tableName 
  311.    * @param cols 
  312.    * @return 
  313.    * @throws IOException 
  314.    */  
  315.     public static ResultScanner getDataMultipleColumnPrefixFilter(String tableName,String... cols) throws IOException{  
  316.         byte[][] prefixes = new byte[cols.length][] ;  
  317.         for (int i = 0; i < cols.length; i++) {  
  318.             prefixes[i] = cols[i].getBytes();  
  319.         }  
  320.         Table table = connection.getTable(TableName.valueOf(tableName));  
  321.         //返回所有行中以name或者age打头的列的数据  
  322.         MultipleColumnPrefixFilter ff = new MultipleColumnPrefixFilter(prefixes);  
  323.         Scan scan = new Scan();  
  324.         scan.setFilter(ff);  
  325.         ResultScanner rs = table.getScanner(scan);    
  326.         return rs;  
  327.     }  
  328.       
  329.     /** 
  330.      * 返回所有列中从a 到 d 打头的范围的数据, 
  331.      * @param tableName 
  332.      * @param startCol 
  333.      * @param endCol 
  334.      * @return 
  335.      * @throws IOException 
  336.      */  
  337.     public static ResultScanner getDataColumnRangeFilter(String tableName,String startCol,String endCol) throws IOException{  
  338.         Table table = connection.getTable(TableName.valueOf(tableName));  
  339.         byte[] startColumn = Bytes.toBytes(startCol);  
  340.         byte[] endColumn = Bytes.toBytes(endCol);  
  341.         //返回所有列中从a到d打头的范围的数据,  
  342.         ColumnRangeFilter ff = new ColumnRangeFilter(startColumn, true, endColumn, true);  
  343.         Scan scan = new Scan();  
  344.         scan.setFilter(ff);  
  345.         ResultScanner rs = table.getScanner(scan);     
  346.         return rs;  
  347.     }  
  348.       
  349.     /** 
  350.      * 返回匹配 row的内容 
  351.      * @param tableName 
  352.      * @param row 
  353.      * @return 
  354.      * @throws IOException 
  355.      */  
  356.     public static ResultScanner getDataRowFilter(String tableName,String row) throws IOException{  
  357.         Table table = connection.getTable(TableName.valueOf(tableName));  
  358.         RowFilter rf = new RowFilter(CompareOp.EQUAL ,   
  359.                 new SubstringComparator(row));  
  360.         //       new BinaryPrefixComparator(value) //匹配字节数组前缀  
  361.         //       new RegexStringComparator(expr) // 正则表达式匹配  
  362.         //       new SubstringComparator(substr)// 子字符串匹配   
  363.         Scan scan = new Scan();  
  364.         scan.setFilter(rf);  
  365.         ResultScanner rs = table.getScanner(scan);     
  366.         return rs;  
  367.     }  
  368.       
  369.     /** 
  370.      * pageFilter 
  371.      * @param tableName 
  372.      * @return 
  373.      * @throws IOException 
  374.      */  
  375.     public static ResultScanner getDataPageFilter(String tableName) throws IOException{  
  376.         Table table = connection.getTable(TableName.valueOf("user"));  
  377.         PageFilter pf = new PageFilter(2L);  
  378.         Scan scan = new Scan();  
  379.         scan.setFilter(pf);  
  380.         scan.setStartRow(Bytes.toBytes("zhangsan_"));  
  381.         ResultScanner rs = table.getScanner(scan);     
  382.         return rs;  
  383.     }  
  384.       
  385.     
  386.     public static ResultScanner getDataSkipFilter(String tableName) throws IOException{  
  387.         Table table = connection.getTable(TableName.valueOf("user"));  
  388.         SkipFilter sf = new SkipFilter(new ValueFilter(CompareOp.NOT_EQUAL,  
  389.                 new BinaryComparator(Bytes.toBytes("zhangsan"))));  
  390.         Scan scan = new Scan();  
  391.         scan.setFilter(sf);  
  392.         ResultScanner rs = table.getScanner(scan);     
  393.         return rs;  
  394.     }  
  395.       
  396.       
  397.     public static ResultScanner getDataFirstKeyOnlyFilter(String tableName) throws IOException{  
  398.         Table table = connection.getTable(TableName.valueOf(tableName));  
  399.          FirstKeyOnlyFilter fkof = new FirstKeyOnlyFilter();  
  400.             Scan scan = new Scan();  
  401.             scan.setFilter(fkof);  
  402.             ResultScanner rs = table.getScanner(scan);    
  403.         return rs;  
  404.     }  
  405.       
  406.       
  407.   
  408.     public static void main(String args[]) throws Exception {  
  409.           
  410.         scanTable("user");  
  411. //      getDataByRow("user", "zhangsan_1495527850759");  
  412. //      putData("user", "wangwu_"+System.currentTimeMillis(), "userid", "id", "009");  
  413. //      getDataByFamilyColumn("user", "userid","id");  
  414. //      scanTable("user");  
  415. //      getDataByRowFilter("user", "zhangsan");  
  416. //      putData("user", "zhangsan_1495527850824", "account", "country", "china");  
  417. //           for (Result result : getDataFirstKeyOnlyFilter("user")) {  
  418. //               List<Cell> cells= result.listCells();      
  419. //               for (Cell cell : cells) {  
  420. //                   String row = Bytes.toString(result.getRow());  
  421. //                   String family1 = Bytes.toString(CellUtil.cloneFamily(cell));  
  422. //                   String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell));  
  423. //                   String value = Bytes.toString(CellUtil.cloneValue(cell));  
  424. //                   System.out.println("[row:"+row+"],[family:"+family1+"],[qualifier:"+qualifier+"]"  
  425. //                          + ",[value:"+value+"],[time:"+cell.getTimestamp()+"]");  
  426. //              }  
  427. //          }  
  428.           
  429.     }  
  430.   
  431. }