Java操作Hbase進行建表、刪表以及對數據進行增刪改查,條件查詢

1、搭建環境

  新建JAVA項目,添加的包有:

   有關Hadoop的hadoop-core-0.20.204.0.jar

   有關Hbase的hbase-0.90.4.jar、hbase-0.90.4-tests.jar以及Hbase資源包中lib目錄下的所有jar包

 

2、主要程序

 

Java代碼  
  1. package com.wujintao.hbase.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.hadoop.conf.Configuration;  
  8. import org.apache.hadoop.hbase.HBaseConfiguration;  
  9. import org.apache.hadoop.hbase.HColumnDescriptor;  
  10. import org.apache.hadoop.hbase.HTableDescriptor;  
  11. import org.apache.hadoop.hbase.KeyValue;  
  12. import org.apache.hadoop.hbase.MasterNotRunningException;  
  13. import org.apache.hadoop.hbase.ZooKeeperConnectionException;  
  14. import org.apache.hadoop.hbase.client.Delete;  
  15. import org.apache.hadoop.hbase.client.Get;  
  16. import org.apache.hadoop.hbase.client.HBaseAdmin;  
  17. import org.apache.hadoop.hbase.client.HTable;  
  18. import org.apache.hadoop.hbase.client.HTablePool;  
  19. import org.apache.hadoop.hbase.client.Put;  
  20. import org.apache.hadoop.hbase.client.Result;  
  21. import org.apache.hadoop.hbase.client.ResultScanner;  
  22. import org.apache.hadoop.hbase.client.Scan;  
  23. import org.apache.hadoop.hbase.filter.Filter;  
  24. import org.apache.hadoop.hbase.filter.FilterList;  
  25. import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;  
  26. import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;  
  27. import org.apache.hadoop.hbase.util.Bytes;  
  28.   
  29. public class JinTaoTest {  
  30.   
  31.     public static Configuration configuration;  
  32.     static {  
  33.         configuration = HBaseConfiguration.create();  
  34.         configuration.set("hbase.zookeeper.property.clientPort", "2181");  
  35.         configuration.set("hbase.zookeeper.quorum", "192.168.1.100");  
  36.         configuration.set("hbase.master", "192.168.1.100:600000");  
  37.     }  
  38.   
  39.     public static void main(String[] args) {  
  40.         // createTable("wujintao");  
  41.         // insertData("wujintao");  
  42.         // QueryAll("wujintao");  
  43.         // QueryByCondition1("wujintao");  
  44.         // QueryByCondition2("wujintao");  
  45.         //QueryByCondition3("wujintao");  
  46.         //deleteRow("wujintao","abcdef");  
  47.         deleteByCondition("wujintao","abcdef");  
  48.     }  
  49.   
  50.     /** 
  51.      * 創建表 
  52.      * @param tableName 
  53.      */  
  54.     public static void createTable(String tableName) {  
  55.         System.out.println("start create table ......");  
  56.         try {  
  57.             HBaseAdmin hBaseAdmin = new HBaseAdmin(configuration);  
  58.             if (hBaseAdmin.tableExists(tableName)) {// 如果存在要創建的表,那麼先刪除,再創建  
  59.                 hBaseAdmin.disableTable(tableName);  
  60.                 hBaseAdmin.deleteTable(tableName);  
  61.                 System.out.println(tableName + " is exist,detele....");  
  62.             }  
  63.             HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);  
  64.             tableDescriptor.addFamily(new HColumnDescriptor("column1"));  
  65.             tableDescriptor.addFamily(new HColumnDescriptor("column2"));  
  66.             tableDescriptor.addFamily(new HColumnDescriptor("column3"));  
  67.             hBaseAdmin.createTable(tableDescriptor);  
  68.         } catch (MasterNotRunningException e) {  
  69.             e.printStackTrace();  
  70.         } catch (ZooKeeperConnectionException e) {  
  71.             e.printStackTrace();  
  72.         } catch (IOException e) {  
  73.             e.printStackTrace();  
  74.         }  
  75.         System.out.println("end create table ......");  
  76.     }  
  77.   
  78.     /** 
  79.      * 插入數據 
  80.      * @param tableName 
  81.      */  
  82.     public static void insertData(String tableName) {  
  83.         System.out.println("start insert data ......");  
  84.         HTablePool pool = new HTablePool(configuration, 1000);  
  85.         HTable table = (HTable) pool.getTable(tableName);  
  86.         Put put = new Put("112233bbbcccc".getBytes());// 一個PUT代表一行數據,再NEW一個PUT表示第二行數據,每行一個唯一的ROWKEY,此處rowkey爲put構造方法中傳入的值  
  87.         put.add("column1".getBytes(), null, "aaa".getBytes());// 本行數據的第一列  
  88.         put.add("column2".getBytes(), null, "bbb".getBytes());// 本行數據的第三列  
  89.         put.add("column3".getBytes(), null, "ccc".getBytes());// 本行數據的第三列  
  90.         try {  
  91.             table.put(put);  
  92.         } catch (IOException e) {  
  93.             e.printStackTrace();  
  94.         }  
  95.         System.out.println("end insert data ......");  
  96.     }  
  97.   
  98.     /** 
  99.      * 刪除一張表 
  100.      * @param tableName 
  101.      */  
  102.     public static void dropTable(String tableName) {  
  103.         try {  
  104.             HBaseAdmin admin = new HBaseAdmin(configuration);  
  105.             admin.disableTable(tableName);  
  106.             admin.deleteTable(tableName);  
  107.         } catch (MasterNotRunningException e) {  
  108.             e.printStackTrace();  
  109.         } catch (ZooKeeperConnectionException e) {  
  110.             e.printStackTrace();  
  111.         } catch (IOException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.   
  115.     }  
  116.     /** 
  117.      * 根據 rowkey刪除一條記錄 
  118.      * @param tablename 
  119.      * @param rowkey 
  120.      */  
  121.      public static void deleteRow(String tablename, String rowkey)  {  
  122.         try {  
  123.             HTable table = new HTable(configuration, tablename);  
  124.             List list = new ArrayList();  
  125.             Delete d1 = new Delete(rowkey.getBytes());  
  126.             list.add(d1);  
  127.               
  128.             table.delete(list);  
  129.             System.out.println("刪除行成功!");  
  130.               
  131.         } catch (IOException e) {  
  132.             e.printStackTrace();  
  133.         }  
  134.           
  135.   
  136.     }  
  137.   
  138.      /** 
  139.       * 組合條件刪除 
  140.       * @param tablename 
  141.       * @param rowkey 
  142.       */  
  143.      public static void deleteByCondition(String tablename, String rowkey)  {  
  144.             //目前還沒有發現有效的API能夠實現 根據非rowkey的條件刪除 這個功能能,還有清空表全部數據的API操作  
  145.   
  146.     }  
  147.   
  148.   
  149.     /** 
  150.      * 查詢所有數據 
  151.      * @param tableName 
  152.      */  
  153.     public static void QueryAll(String tableName) {  
  154.         HTablePool pool = new HTablePool(configuration, 1000);  
  155.         HTable table = (HTable) pool.getTable(tableName);  
  156.         try {  
  157.             ResultScanner rs = table.getScanner(new Scan());  
  158.             for (Result r : rs) {  
  159.                 System.out.println("獲得到rowkey:" + new String(r.getRow()));  
  160.                 for (KeyValue keyValue : r.raw()) {  
  161.                     System.out.println("列:" + new String(keyValue.getFamily())  
  162.                             + "====值:" + new String(keyValue.getValue()));  
  163.                 }  
  164.             }  
  165.         } catch (IOException e) {  
  166.             e.printStackTrace();  
  167.         }  
  168.     }  
  169.   
  170.     /** 
  171.      * 單條件查詢,根據rowkey查詢唯一一條記錄 
  172.      * @param tableName 
  173.      */  
  174.     public static void QueryByCondition1(String tableName) {  
  175.   
  176.         HTablePool pool = new HTablePool(configuration, 1000);  
  177.         HTable table = (HTable) pool.getTable(tableName);  
  178.         try {  
  179.             Get scan = new Get("abcdef".getBytes());// 根據rowkey查詢  
  180.             Result r = table.get(scan);  
  181.             System.out.println("獲得到rowkey:" + new String(r.getRow()));  
  182.             for (KeyValue keyValue : r.raw()) {  
  183.                 System.out.println("列:" + new String(keyValue.getFamily())  
  184.                         + "====值:" + new String(keyValue.getValue()));  
  185.             }  
  186.         } catch (IOException e) {  
  187.             e.printStackTrace();  
  188.         }  
  189.     }  
  190.   
  191.     /** 
  192.      * 單條件按查詢,查詢多條記錄 
  193.      * @param tableName 
  194.      */  
  195.     public static void QueryByCondition2(String tableName) {  
  196.   
  197.         try {  
  198.             HTablePool pool = new HTablePool(configuration, 1000);  
  199.             HTable table = (HTable) pool.getTable(tableName);  
  200.             Filter filter = new SingleColumnValueFilter(Bytes  
  201.                     .toBytes("column1"), null, CompareOp.EQUAL, Bytes  
  202.                     .toBytes("aaa")); // 當列column1的值爲aaa時進行查詢  
  203.             Scan s = new Scan();  
  204.             s.setFilter(filter);  
  205.             ResultScanner rs = table.getScanner(s);  
  206.             for (Result r : rs) {  
  207.                 System.out.println("獲得到rowkey:" + new String(r.getRow()));  
  208.                 for (KeyValue keyValue : r.raw()) {  
  209.                     System.out.println("列:" + new String(keyValue.getFamily())  
  210.                             + "====值:" + new String(keyValue.getValue()));  
  211.                 }  
  212.             }  
  213.         } catch (Exception e) {  
  214.             e.printStackTrace();  
  215.         }  
  216.   
  217.     }  
  218.   
  219.     /** 
  220.      * 組合條件查詢 
  221.      * @param tableName 
  222.      */  
  223.     public static void QueryByCondition3(String tableName) {  
  224.   
  225.         try {  
  226.             HTablePool pool = new HTablePool(configuration, 1000);  
  227.             HTable table = (HTable) pool.getTable(tableName);  
  228.   
  229.             List<Filter> filters = new ArrayList<Filter>();  
  230.   
  231.             Filter filter1 = new SingleColumnValueFilter(Bytes  
  232.                     .toBytes("column1"), null, CompareOp.EQUAL, Bytes  
  233.                     .toBytes("aaa"));  
  234.             filters.add(filter1);  
  235.   
  236.             Filter filter2 = new SingleColumnValueFilter(Bytes  
  237.                     .toBytes("column2"), null, CompareOp.EQUAL, Bytes  
  238.                     .toBytes("bbb"));  
  239.             filters.add(filter2);  
  240.   
  241.             Filter filter3 = new SingleColumnValueFilter(Bytes  
  242.                     .toBytes("column3"), null, CompareOp.EQUAL, Bytes  
  243.                     .toBytes("ccc"));  
  244.             filters.add(filter3);  
  245.   
  246.             FilterList filterList1 = new FilterList(filters);  
  247.   
  248.             Scan scan = new Scan();  
  249.             scan.setFilter(filterList1);  
  250.             ResultScanner rs = table.getScanner(scan);  
  251.             for (Result r : rs) {  
  252.                 System.out.println("獲得到rowkey:" + new String(r.getRow()));  
  253.                 for (KeyValue keyValue : r.raw()) {  
  254.                     System.out.println("列:" + new String(keyValue.getFamily())  
  255.                             + "====值:" + new String(keyValue.getValue()));  
  256.                 }  
  257.             }  
  258.             rs.close();  
  259.   
  260.         } catch (Exception e) {  
  261.             e.printStackTrace();  
  262.         }  
  263.   
  264.     }  
  265.   
  266. }  

 注意:可能大家沒看到更新數據的操作,其實更新的操作跟添加完全一致,只不過是添加呢rowkey不存在,更新呢rowkey已經存在,並且timstamp相同的情況下,還有就是目前好像還沒辦法實現hbase數據的分頁查詢,不知道有沒有人知道怎麼做

 

HBase性能優化建議:

 針對前面的代碼,有很多不足之處,在此我就不修改上面的代碼了,只是提出建議的地方,大家自己加上

   1)配置

  當你調用create方法時將會加載兩個配置文件:hbase-default.xml and hbase-site.xml,利用的是當前的java類路徑, 代碼中configuration設置的這些配置將會覆蓋hbase-default.xml和hbase-site.xml中相同的配置,如果兩個配置文件都存在並且都設置好了相應參上面的屬性下面的屬性即可

 

 2)關於建表

  

public void createTable(HTableDescriptor desc)

 

HTableDescriptor 代表的是表的schema, 提供的方法中比較有用的有

setMaxFileSize,指定最大的region size

setMemStoreFlushSize 指定memstore flush到HDFS上的文件大小

增加family通過 addFamily方法

 

public void addFamily(final HColumnDescriptor family)

 

HColumnDescriptor 代表的是column的schema,提供的方法比較常用的有

setTimeToLive:指定最大的TTL,單位是ms,過期數據會被自動刪除。

setInMemory:指定是否放在內存中,對小表有用,可用於提高效率。默認關閉

setBloomFilter:指定是否使用BloomFilter,可提高隨機查詢效率。默認關閉

setCompressionType:設定數據壓縮類型。默認無壓縮。

setMaxVersions:指定數據最大保存的版本個數。默認爲3。

 

注意的是,一般我們不去setInMemory爲true,默認是關閉的

 

3)關於入庫

   官方建議

 table.setAutoFlush(false); //數據入庫之前先設置此項爲false

 table.setflushCommits();//入庫完成後,手動刷入數據

注意:

  在入庫過程中,put.setWriteToWAL(true/flase);

  關於這一項如果不希望大量數據在存儲過程中丟失,建議設置爲true,如果僅是在測試演練階段,爲了節省入庫時間建議設置爲false

 

4)關於獲取表實例

HTablePool pool = new HTablePool(configuration, Integer.MAX_VALUE);

HTable table = (HTable) pool.getTable(tableName);

建議用表連接池的方式獲取表,具體池有什麼作用,我想用過數據庫連接池的同學都知道,我就不再重複

不建議使用new HTable(configuration,tableName);的方式獲取表

 

5)關於查詢

 建議每個查詢語句都放入try catch語句塊,並且finally中要進行關閉ResultScanner實例以及將不使用的表重新放入到HTablePool中的操作,具體做法如下

 

Java代碼  
  1. public static void QueryAll(String tableName) {  
  2.         HTablePool pool = new HTablePool(configuration, Integer.MAX_VALUE);  
  3.         HTable table = null;  
  4.         ResultScanner rs = null;  
  5.         try {  
  6.             Scan scan = new Scan();  
  7.             table = (HTable) pool.getTable(tableName);  
  8.             rs = table.getScanner(scan);  
  9.             for (Result r : rs) {  
  10.                 System.out.println("獲得到rowkey:" + new String(r.getRow()));  
  11.                 for (KeyValue keyValue : r.raw()) {  
  12.                     System.out.println("列:" + new String(keyValue.getFamily())  
  13.                             + "====值:" + new String(keyValue.getValue()));  
  14.                 }  
  15.             }  
  16.         } catch (IOException e) {  
  17.             e.printStackTrace();  
  18.         }finally{  
  19.             rs.close();// 最後還得關閉  
  20.             pool.putTable(table); //實際應用過程中,pool獲取實例的方式應該抽取爲單例模式的,不應在每個方法都重新獲取一次(單例明白?就是抽取到專門獲取pool的邏輯類中,具體邏輯爲如果pool存在着直接使用,如果不存在則new)  
  21.         }  
  22.     }  

 

 所以,以上代碼有缺陷的地方,感興趣的同學可以針對優化建議作出相應修改

發佈了6 篇原創文章 · 獲贊 40 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章