- By Steve Haines
- Setting Up an HBase Maven Project
- Summary
Setting Up an HBase Maven Project
To develop HBase client applications, you either need to download the HBase client library and add it to your CLASSPATH, or you can use Maven to manage your dependencies. You can download the source code for this article here, but if you want to follow along, execute the following Maven command to create the project:
mvn archetype:create -DgroupId=com.geekcap.informit -DartifactId=hbase-example
This creates a new directory named hbase-example in your working directory. The first thing you need to do is add the hbase-client dependency to your pom.xml file. Listing 1 shows the contents of my pom.xml file.
Listing 1. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.geekcap.informit</groupId> <artifactId>hbase-example</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>hbase-example</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>0.98.5-hadoop2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>com.geekcap.informit.hbaseexample.HBaseExample</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy</id> <phase>install</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
This pom.xml file has the hbase-client dependency in it:
<dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>0.98.5-hadoop2</version> </dependency>
It also has some build settings to compile the code against Java 1.6 to make the resultant JAR file executable and to include all dependencies in the build. When you build then you can execute our main() method with the following command from the target directory:
java jar hbase-example-1.0-SNAPSHOT.jar
The first thing that we need to do in our application is to gain access to the PageViews table that we created in the previous article. We can ask HBase for a connection to the PageViews table in one of two ways:
- Create an HTable instance directly.
- Use a connection pool.
Using a connection pool performs better because creating a database connection is an expensive operation, but let’s start by creating the HTable instance directly:
Configuration conf = HBaseConfiguration.create(); HTableInterface pageViewTable = new HTable( conf, "PageViews" );
The HBaseConfiguration class has a static method, create(), that creates a configuration object. The default configuration is to connect to HBase running on the local machine, but if you want to change any of the connection parameters, you can do so by calling the Configuration class’s set() method. HBase runs on top of Hadoop, and Hadoop leverages a technology called ZooKeeper to handle its load distribution, so if you want to connect to a remote machine, you could do so as follows:
conf.set("hbase.zookeeper.quorum", "server’s IP address");
The HTable constructor takes a configuration object and the name of the table to connect to.
The alternative approach is to create an HTablePool:
HTablePool pool = new HTablePool();
Or you can specify a connection and a pool size as follows:
HTablePool pool = new HTablePool(conf,10);
This creates a new HTablePool with 10 as the maximum number of references to maintain for each table. This means that after accessing the PageViews table, you will get back the same connection without having to re-create it. And if you run concurrent threads, then you can have 10 simultaneous connections.) With an HTablePool youcan access the HTable with the following command:
HTableInterface pageViewsTable = pool.getTable("PageViews");
And then when you finish, you can close the table to return the connection back to the pool:
pageViewsTable.close();
To interact with HBase, I created a simple PageView POJO class, as shown in Listing 2.
Listing 2. PageView.java
package com.geekcap.informit.hbaseexample; public class PageView { private String userId; private String page; public PageView() { } public PageView(String userId, String page) { this.userId = userId; this.page = page; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } }
In this example we’re going to store two pieces of informationthe user ID and the page that the user visitedand we’re going to save the user ID as the row key. Programming against the HBase API is similar to what we learned in the previous article. Specifically, we accomplish the following actions with the following commands:
- Get an object instance from the database: Createa Get object and pass it to the HTableInterface’s get() method.
- Put an object instance into the database: Createa Put object and pass it to the HTableInterface’s put() method.
- Delete an object instance from the database: Createa Delete object and pass it to the HTableInstance’s delete() method.
- Scan the database for rows within start and end row values: Createa Scan object and pass it to the HTableInstance’s getScanner() method.
Listing 3 shows the source code for the HBaseExample class.
Listing 3. HBaseExample.java
package com.geekcap.informit.hbaseexample; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HBaseExample { private HTableInterface pageViewTable; public HBaseExample() { try { Configuration conf = HBaseConfiguration.create(); pageViewTable = new HTable( conf, "PageViews"); } catch (IOException e) { e.printStackTrace(); } } public void close() { try { pageViewTable.close(); } catch (IOException e) { e.printStackTrace(); } } public void put( PageView pageView ) { // Create a new Put object with the Row Key as the bytes of the user id Put put = new Put( Bytes.toBytes( pageView.getUserId() ) ); // Add the user id to the info column family put.add( Bytes.toBytes( "info" ), Bytes.toBytes( "userId" ), Bytes.toBytes( pageView.getUserId() ) ); // Add the page to the info column family put.add( Bytes.toBytes( "info" ), Bytes.toBytes( "page" ), Bytes.toBytes( pageView.getPage() ) ); try { // Add the PageView to the page view table pageViewTable.put( put ); } catch( IOException e ) { e.printStackTrace(); } } public PageView get( String rowkey ) { try { // Create a Get object with the rowkey (as a byte[]) Get get = new Get( Bytes.toBytes( rowkey ) ); // Execute the Get Result result = pageViewTable.get( get ); // Retrieve the results PageView pageView = new PageView(); byte[] bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "userId" ) ); pageView.setUserId( Bytes.toString( bytes ) ); bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "page" ) ); pageView.setPage(Bytes.toString(bytes)); // Return the newly constructed PageView return pageView; } catch (IOException e) { e.printStackTrace(); } return null; } public void delete( String rowkey ) { try { Delete delete = new Delete( Bytes.toBytes( rowkey ) ); pageViewTable.delete( delete ); } catch (IOException e) { e.printStackTrace(); } } public List<PageView> scan( String startRowKey, String endRowKey ) { try { // Build a list to hold our results List<PageView> pageViewResults = new ArrayList<PageView>(); // Create and execute a scan Scan scan = new Scan( Bytes.toBytes( startRowKey ), Bytes.toBytes( endRowKey ) ); ResultScanner results = pageViewTable.getScanner(scan); for( Result result : results ) { // Build a new PageView PageView pageView = new PageView(); byte[] bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "userId" ) ); pageView.setUserId( Bytes.toString( bytes ) ); bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "page" ) ); pageView.setPage(Bytes.toString(bytes)); // Add the PageView to our results pageViewResults.add( pageView ); } // Return our results return pageViewResults; } catch (IOException e) { e.printStackTrace(); } return null; } public static void main( String[] args ) { HBaseExample example = new HBaseExample(); // Create two records example.put( new PageView( "User1", "/mypage" ) ); example.put( new PageView( "User2","/mypage" ) ); // Execute a Scan from "U" to "V" List<PageView> pageViews = example.scan( "U", "V" ); if( pageViews != null ) { System.out.println("Page Views:"); for (PageView pageView : pageViews) { System.out.println("\tUser ID: " + pageView.getUserId() + ", Page: " + pageView.getPage()); } } // Get a specific row PageView pv = example.get( "User1" ); System.out.println( "User ID: " + pv.getUserId() + ", Page: " + pv.getPage() ); // Delete a row example.delete( "User1" ); // Execute another scan, which should just have User2 in it pageViews = example.scan( "U", "V" ); if( pageViews != null ) { System.out.println("Page Views:"); for (PageView pageView : pageViews) { System.out.println("\tUser ID: " + pageView.getUserId() + ", Page: " + pageView.getPage()); } } // Close our table example.close(); } }
Listing 3 creates a Configuration instance, connects to the PageViews database in its constructor, and then saves a reference to the HTableInterface as a class member variable. Let’s look at the methods one-by-one, starting withthe put() method:
public void put( PageView pageView ) { // Create a new Put object with the Row Key as the bytes of the user id Put put = new Put( Bytes.toBytes( pageView.getUserId() ) ); // Add the user id to the info column family put.add( Bytes.toBytes( "info" ), Bytes.toBytes( "userId" ), Bytes.toBytes( pageView.getUserId() ) ); // Add the page to the info column family put.add( Bytes.toBytes( "info" ), Bytes.toBytes( "page" ), Bytes.toBytes( pageView.getPage() ) ); try { // Add the PageView to the page view table pageViewTable.put( put ); } catch( IOException e ) { e.printStackTrace(); } }
The put() method creates a new Put object, passing it the row key. The only thing that you need to keep in mind is that all objects are stored as an array of bytes, so we need to convert the row key String value to a byte[]. We can do that with the Bytes.toBytes() method. The constructor for the Put objects requires the row key, but then we need to add our fields. Recall that we created a column family named (info) and now we have two column qualifiers: userId and page. Again we need to convert the column family, column qualifier, and associated value to byte arrays, and then we can add them to the Put object using the add() method. Finally, we can call the HTableInterface’s put() method with the Put object to insert the record in the database.
The next method we want to examine is the get() method:
public PageView get( String rowkey ) { try { // Create a Get object with the rowkey (as a byte[]) Get get = new Get( Bytes.toBytes( rowkey ) ); // Execute the Get Result result = pageViewTable.get( get ); // Retrieve the results PageView pageView = new PageView(); byte[] bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "userId" ) ); pageView.setUserId( Bytes.toString( bytes ) ); bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "page" ) ); pageView.setPage(Bytes.toString(bytes)); // Return the newly constructed PageView return pageView; } catch (IOException e) { e.printStackTrace(); } return null; }
The get() method creates a Get object, passing it a byte array representation of the row key, and then executes the HTableInterface’s get() method, passing it our Get instance. This method returns a Result instance that we can use to retrieve the values we’re looking for. We can pass the Result class’s getValue() method the column family (“info”) and the column qualifier we want, as byte arrays, and it returns a byte array that contains the requested value.
Next, let’s review the delete() method:
public void delete( String rowkey ) { try { Delete delete = new Delete( Bytes.toBytes( rowkey ) ); pageViewTable.delete( delete ); } catch (IOException e) { e.printStackTrace(); } }
The delete() method is the simplest: It creates a Delete object with a byte array representation of the row key to delete, and then it invokes the HTableInterface’s delete() method.
Finally, let’s review the scan() method:
public List<PageView> scan( String startRowKey, String endRowKey ) { try { // Build a list to hold our results List<PageView> pageViewResults = new ArrayList<PageView>(); // Create and execute a scan Scan scan = new Scan( Bytes.toBytes( startRowKey ), Bytes.toBytes( endRowKey ) ); ResultScanner results = pageViewTable.getScanner(scan); for( Result result : results ) { // Build a new PageView PageView pageView = new PageView(); byte[] bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "userId" ) ); pageView.setUserId( Bytes.toString( bytes ) ); bytes = result.getValue( Bytes.toBytes( "info" ), Bytes.toBytes( "page" ) ); pageView.setPage(Bytes.toString(bytes)); // Add the PageView to our results pageViewResults.add( pageView ); } // Return our results return pageViewResults; } catch (IOException e) { e.printStackTrace(); } return null; }
The scan() method is the most complicated method, but if you remember how table scans work from the first article, it should be straightforward. Recall that you cannot query a table, but you can retrieve all records between two row keys. So in this example we create a Scan object, passing it start and end row keys (as byte arrays). We then pass this Scan object to the HTableInterface’s getScanner() method, which returns a ResultScanner. We can iterate over the ResultScanner and handle the results just as we handle the Result in the get() method.
Finally, the main() method demonstrates how to exercise these methods. One note is that we have to close the table when we’re complete, so we added a close() method that closes the HTableInterface.
You can build this application with the following command:
mvn clean install
This creates a file in the target directory named hbase-example-1.0-SNAPSHOT.jar. You can execute it with the following command:
java -jar hbase-example-1.0-SNAPSHOT.jar
You should see output similar to the following:
Page Views:
- User ID: User1, Page: /mypage
- User ID: User2, Page: /mypage
User ID: User1, Page: /mypage
Page Views:
- User ID: User2, Page: /mypage
We created two page views and then executed a table scan for rows between “U” and “V”; then we retrieved a specific row; we deleted the first page view; and finally we ran a second table scan.