Data random access using Java client APIs

The earlier recipe introduced the command-line interface for HBase. This recipe demonstrates how we can talk to HBase using the Java API.

Getting ready

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.

How to do it...

The following steps explain how to connect to HBase via a Java client, store, and retrieve data from the client.

  1. Unzip the sample code for this chapter. We will call the new directory 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");
  2. Store the data in HBase:
    Put put = new Put("row1".getBytes());
    put.add("cf".getBytes(), "b".getBytes(), "val2".getBytes());
    table.put(put);
  3. Search for data by doing a scan.
    Scan s = new Scan();
    s.addFamily(Bytes.toBytes("cf")); 
    ResultScanner results = table.getScanner(s);
  4. Then let us print the results:
    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();
    }
  5. Edit the value for the hbase.home property in SAMPLE5_DIR/build.xml.
  6. Compile the Sample by running the following command from SAMPLE5_DIR.
    >ant hbase-build
    
  7. Run the sample by running the following command from SAMPLE5_DIR.
    >ant hbase-run-javaclient
    

If all works well, this will print the content of the HBase table to the console.

How it works...

When you run the commands, Ant will run the Java HBase client we had written. It will connect to the HBase server and issue commands to store and search data in HBase storage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset