This chapter provides information about performing operations using HBase native APIs. This information is not exhaustive, and provides a quick reference in addition to the User API Reference. The examples here are not comprehensive or complete, and should be used for purposes of illustration only.
Apache HBase also works with multiple external APIs. See Chapter 11, Apache HBase External APIs for more information.
Example 10.1. Create a Table Using Java
This example has been tested on HBase 0.96.1.1.
package com.example.hbase.admin; import java.io.IOException; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.io.compress.Compression.Algorithm; import org.apache.hadoop.conf.Configuration; import static com.example.hbase.Constants.*; public class CreateSchema { public static void createOrOverwrite(HBaseAdmin admin, HTableDescriptor table) throws IOException { if (admin.tableExists(table.getName())) { admin.disableTable(table.getName()); admin.deleteTable(table.getName()); } admin.createTable(table); } public static void createSchemaTables (Configuration config) { try { final HBaseAdmin admin = new HBaseAdmin(config); HTableDescriptor table = new HTableDescriptor(TableName.valueOf(TABLE_NAME)); table.addFamily(new HColumnDescriptor(CF_DEFAULT).setCompressionType(Algorithm.SNAPPY)); System.out.print("Creating table. "); createOrOverwrite(admin, table); System.out.println(" Done."); admin.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } }
Example 10.2. Add, Modify, and Delete a Table
This example has been tested on HBase 0.96.1.1.
public static void upgradeFrom0 (Configuration config) { try { final HBaseAdmin admin = new HBaseAdmin(config); TableName tableName = TableName.valueOf(TABLE_ASSETMETA); HTableDescriptor table_assetmeta = new HTableDescriptor(tableName); table_assetmeta.addFamily(new HColumnDescriptor(CF_DEFAULT).setCompressionType(Algorithm.SNAPPY)); // Create a new table. System.out.print("Creating table_assetmeta. "); admin.createTable(table_assetmeta); System.out.println(" Done."); // Update existing table HColumnDescriptor newColumn = new HColumnDescriptor("NEWCF"); newColumn.setCompactionCompressionType(Algorithm.GZ); newColumn.setMaxVersions(HConstants.ALL_VERSIONS); admin.addColumn(tableName, newColumn); // Disable an existing table admin.disableTable(tableName); // Delete an existing column family admin.deleteColumn(tableName, CF_DEFAULT); // Delete a table (Need to be disabled first) admin.deleteTable(tableName); admin.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }