HBASE & Java: Create a Table

(Last Updated On: )

This tutorial will guide you through how to create a HBASE table using Java 8. Make sure you first follow this tutorial on connecting to HBASE.

Table Exists:

This checks if the table already exists in HBASE.

import org.apache.hadoop.hbase.TableName;

final TableName table = TableName.valueOf(yourTableName);

//Use the connection object to getAdmin from the connection tutorial above.
conn.getAdmin().tableExists(table);

Create Table:

In the most basic example of creating a HBASE table you need to know the name and the column families. A column family is columns grouped together. The data is related in some way and stored together on disk. Notice how we don’t define columns in the table design. Columns are added as we put data. Which I will give example below.

import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;

final TableName table = TableName.valueOf(yourTableName);

final HTableDescriptor hTableBuilder = new HTableDescriptor(table);
final HColumnDescriptor column = new HColumnDescriptor(family);
hTableBuilder.addFamily(column);

//Use the connection object to getAdmin from the connection tutorial above.
conn.getAdmin().createTable(hTableBuilder);

Get a Table:

This will retrieve a table from HBASE so you can use it to put data, etc.

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Table;

final TableName table = TableName.valueOf(yourTableName);

//Use the connection object from the connection tutorial above.
final Table table = conn.getTable(table);

Put Data:

Now we will put data into the table we have reference to above. Notice how the columns are referenced.

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

final byte[] rowKey = Bytes.toBytes("some row identifier");
final byte[] columnFamily = Bytes.toBytes("myFamily");
final byte[] columnName = Bytes.toBytes("columnName");
final byte[] data = Bytes.toBytes(myData);

final Put put = new Put(rowKey);
put.addColumn(columnFamily, columnName, data);

//Insert the data.
table.put(put);
//Close the table.
table.close();

One thought on “HBASE & Java: Create a Table”

Comments are closed.