Saturday, February 28, 2015

Getting data from HBase in Java



1. Make sure that the HBase configuration file is in your classpath when you run the program

                /**
* Create a HBase Table for employees
*/
// Create a HBase Configuration
Configuration conf = HBaseConfiguration.create();
// Create an instance of the HBaseAdmin to connect to HBase
HBaseAdmin admin = new HBaseAdmin(conf);
// Create a table
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("employee"));
tableDescriptor.addFamily(new HColumnDescriptor("personalinfo"));
tableDescriptor.addFamily(new HColumnDescriptor("workinfo"));
admin.createTable(tableDescriptor);
/**
* Add a record to the table
*/
// Get the Table instance
HTable table = new HTable(conf, "employee");
// Create a Row with key as combination of name, department, subdepartment, and employee number
Put put = new Put(Bytes.toBytes("Sam-IT-Infrastructure-43"));
// Add data to the families in the row
put.add(Bytes.toBytes("personalinfo"), Bytes.toBytes("firstName"), Bytes.toBytes("Sam"));
put.add(Bytes.toBytes("personalinfo"), Bytes.toBytes("lastName"), Bytes.toBytes("Witwicky"));
put.add(Bytes.toBytes("personalinfo"), Bytes.toBytes("gender"), Bytes.toBytes("M"));
put.add(Bytes.toBytes("workinfo"), Bytes.toBytes("email"), Bytes.toBytes("samwitwicky@abcorp.com"));
put.add(Bytes.toBytes("workinfo"), Bytes.toBytes("experience"), Bytes.toBytes("5"));
table.put(put);
table.flushCommits();
table.close();
/**
* Update a record in the table
*/
// Get the Table instance
table = new HTable(conf, "employee");
// The row with key as combination of name, department, subdepartment, and employee number
Put updatePut = new Put(Bytes.toBytes("Sam-IT-Infrastructure-43"));
// Update experience and add designation
updatePut.add(Bytes.toBytes("workinfo"), Bytes.toBytes("experience"), Bytes.toBytes("6"));
updatePut.add(Bytes.toBytes("workinfo"), Bytes.toBytes("designation"), Bytes.toBytes("Senior Designer"));
table.put(updatePut);
table.flushCommits();
table.close();
/**
* Delete a record in the table
*/
// Get the Table instance
table = new HTable(conf, "employee");
// Delete the row
Delete delete = new Delete(Bytes.toBytes("Sam-IT-Infrastructure-43"));
table.delete(delete);
table.flushCommits();
table.close();

No comments :