wiki:NCHCCloudCourse100929_4_HBExp
HBase 進階課程
程式範例練習

回課程大綱 << 第一關 > 下一關

範例一:新增Table

  • 看懂以下程式碼,並成功執行它
package org.nchc.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.util.GenericOptionsParser;

public class CreateTable {
	public static void createHBaseTable(String tablename, String family)
			throws IOException {
		// HTableDescriptor contains the name of an HTable, and its column
		// families
		// HTableDescriptor 用來描述table的屬性
		HTableDescriptor htd = new HTableDescriptor(tablename);
		// HColumnDescriptor HColumnDescriptor contains information about a
		// column family such as the number of versions, compression settings,
		// etc.
		// HTableDescriptor 透過 add() 方法來加入Column family

		htd.addFamily(new HColumnDescriptor(family));

		// HBaseConfiguration 能接收 hbase-site.xml 的設定值
		HBaseConfiguration config = new HBaseConfiguration();
		// 檔案的操作則使用 HBaseAdmin
		HBaseAdmin admin = new HBaseAdmin(config);
		// 檢查
		if (admin.tableExists(tablename)) {
			System.out.println("Table: " + tablename + "Existed.");
		} else {
			System.out.println("create new table: " + tablename);
			// 建立
			admin.createTable(htd);
		}
	}

	static public void main(String argv[]) throws IOException {
		
		String[] otherArgs = new GenericOptionsParser(new Configuration(), argv)
				.getRemainingArgs();
		if (otherArgs.length < 2) {
			System.out.println("CreateTable <newTableName> <Family>");
			return;
		}
		
		String tablename = otherArgs[0];
		String family = otherArgs[1];

		System.out.println("1. create table :" + tablename);

		createHBaseTable(tablename, family);
	}
}

Last modified 14 years ago Last modified on Sep 27, 2010, 6:24:03 PM