The earlier recipe introduced the command-line interface for HBase. This recipe demonstrates how we can talk to HBase using the Java API.
Install and start HBase as described in the Installing HBase recipe.
To compile and run the sample, you would need to have Apache Ant installed in your machine. If Apache Ant has not been installed already, install it by following the instructions given in http://ant.apache.org/manual/install.html.
The following steps explain how to connect to HBase via a Java client, store, and retrieve data from the client.
SAMPLE5_DIR
. You can find the Java HBase sample from SAMPLE5_DIR/src/chapter5/HBaseClient.java
. The client would look like the following. Here, 60000
is the port of HBase and the localhost is the host where HBase master is running. If you connect from a different machine or are running HBase on a different port, you should change these values accordingly.Configuration conf = HBaseConfiguration.create(); conf.set("hbase.master","localhost:60000"); HTable table = new HTable(conf, "test");
Put put = new Put("row1".getBytes()); put.add("cf".getBytes(), "b".getBytes(), "val2".getBytes()); table.put(put);
Scan s = new Scan(); s.addFamily(Bytes.toBytes("cf")); ResultScanner results = table.getScanner(s);
try { for(Result result: results) { KeyValue[] keyValuePairs = result.raw(); System.out.println(new String(result.getRow())); for(KeyValuekeyValue: keyValuePairs) { System.out.println( new String(keyValue.getFamily()) + " " + new String(keyValue.getQualifier()) + "=" + new String(keyValue.getValue())); } } } finally { results.close(); }
hbase.home
property in SAMPLE5_DIR/build.xml
.SAMPLE5_DIR
.>ant hbase-build
SAMPLE5_DIR
.>ant hbase-run-javaclient
If all works well, this will print the content of the HBase table to the console.