| 1 | {{{ |
| 2 | #!html |
| 3 | <div style="text-align: center; color:#151B8D"><big style="font-weight: bold;"><big><big> |
| 4 | HBase 進階課程 |
| 5 | </big></big></big></div> <div style="text-align: center; color:#7E2217"><big style="font-weight: bold;"><big> |
| 6 | 程式範例練習 |
| 7 | </big></big></div> |
| 8 | }}} |
| 9 | |
| 10 | [wiki:NCHCCloudCourse100928 回課程大綱 << ] 第一關 [wiki:NCHCCloudCourse100929_4_HBEX2 > 下一關 ] |
| 11 | |
| 12 | = 範例一:新增Table = |
| 13 | |
| 14 | * 看懂以下程式碼,並成功執行它 |
| 15 | |
| 16 | {{{ |
| 17 | package org.nchc.hbase; |
| 18 | |
| 19 | import java.io.IOException; |
| 20 | |
| 21 | import org.apache.hadoop.conf.Configuration; |
| 22 | import org.apache.hadoop.hbase.HBaseConfiguration; |
| 23 | import org.apache.hadoop.hbase.HColumnDescriptor; |
| 24 | import org.apache.hadoop.hbase.HTableDescriptor; |
| 25 | import org.apache.hadoop.hbase.client.HBaseAdmin; |
| 26 | import org.apache.hadoop.util.GenericOptionsParser; |
| 27 | |
| 28 | public class CreateTable { |
| 29 | public static void createHBaseTable(String tablename, String family) |
| 30 | throws IOException { |
| 31 | // HTableDescriptor contains the name of an HTable, and its column |
| 32 | // families |
| 33 | // HTableDescriptor 用來描述table的屬性 |
| 34 | HTableDescriptor htd = new HTableDescriptor(tablename); |
| 35 | // HColumnDescriptor HColumnDescriptor contains information about a |
| 36 | // column family such as the number of versions, compression settings, |
| 37 | // etc. |
| 38 | // HTableDescriptor 透過 add() 方法來加入Column family |
| 39 | |
| 40 | htd.addFamily(new HColumnDescriptor(family)); |
| 41 | |
| 42 | // HBaseConfiguration 能接收 hbase-site.xml 的設定值 |
| 43 | HBaseConfiguration config = new HBaseConfiguration(); |
| 44 | // 檔案的操作則使用 HBaseAdmin |
| 45 | HBaseAdmin admin = new HBaseAdmin(config); |
| 46 | // 檢查 |
| 47 | if (admin.tableExists(tablename)) { |
| 48 | System.out.println("Table: " + tablename + "Existed."); |
| 49 | } else { |
| 50 | System.out.println("create new table: " + tablename); |
| 51 | // 建立 |
| 52 | admin.createTable(htd); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | static public void main(String argv[]) throws IOException { |
| 57 | |
| 58 | String[] otherArgs = new GenericOptionsParser(new Configuration(), argv) |
| 59 | .getRemainingArgs(); |
| 60 | if (otherArgs.length < 2) { |
| 61 | System.out.println("CreateTable <newTableName> <Family>"); |
| 62 | return; |
| 63 | } |
| 64 | |
| 65 | String tablename = otherArgs[0]; |
| 66 | String family = otherArgs[1]; |
| 67 | |
| 68 | System.out.println("1. create table :" + tablename); |
| 69 | |
| 70 | createHBaseTable(tablename, family); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | }}} |
| 75 | |