Home > Articles > Data

  • Print
  • + Share This
Like this article? We recommend

Map Reduce in HBase

So how does this correlate to analyzing data in HBase? Let’s walk through the aforementioned steps, but think in terms of HBase, using HBase as a data source and a sink (the destination for the output):

  1. HBase provides a TableInputFormat, to which you provided a table scan, that splits the rows resulting from the table scan into the regions in which those rows reside.
  2. The map process is passed an ImmutableBytesWritable that contains the row key for a row and a Result that contains the columns for that row.
  3. The map process outputs its key/value pair based on its business logic in whatever form makes sense to your application.
  4. The reduce process builds its results but emits the row key as an ImmutableBytesWritable and a Put command to store the results back to HBase.
  5. Finally, the results are stored in HBase by the HBase MapReduce infrastructure. (You do not need to execute the Put commands.)

Let’s put together an example that uses HBase as a sink (the source of data) and outputs its results to a text file on the local file system. For this example we’re going to build on the PageViews table in the previous articles as follows:

  • The row key is an MD5 hash of the user’s name concatenated with the timestamp of the page view as a long.
  • The info column family has two columns: the userId of the user that viewed the page and the page itself.

To start, you need to insert some data. Listing 1 shows the source code for a class named ExampleSetup that insert 10,000 sample rows into the database.

Listing 1. ExampleSetup.java

package com.geekcap.informit.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Random;

 * Helper class that inserts data for us to analyze
public class ExampleSetup
    public static MessageDigest md5;
    public static Random random = new Random();
    static {
        try {
            // Create an MD5 Hash object
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {

     * Generates a row key that contains an MD5 hash of the specified user ID and a random date in the year 2014 but
     * with a random month, day, and time
     * @param userId    The user ID for which to generate the row key
     * @return          A byte[] that contains the row key
    public static byte[] generateRowKey( String userId )
        // Create an MD5 Hash of the User ID
        byte[] userIdHash = md5.digest( userId.getBytes() );

        // Generate a random timestamp
        Calendar calendar = Calendar.getInstance();
        calendar.set( Calendar.YEAR, 2014 );
        calendar.set( Calendar.MONTH, random.nextInt( 12 ) );
        calendar.set( Calendar.DAY_OF_MONTH, random.nextInt( 27 ) + 1 );
        calendar.set( Calendar.HOUR_OF_DAY, random.nextInt( 24 ) );
        calendar.set( Calendar.MINUTE, random.nextInt( 60 ) );
        calendar.set( Calendar.SECOND, random.nextInt( 60 ) );
        byte[] timestamp = Bytes.toBytes(calendar.getTimeInMillis());

        // 16 bytes for MD5 length + size of a Long
        byte[] rowkey = new byte[ 16 + Long.SIZE/8 ];
        int offset = 0;
        offset = Bytes.putBytes( rowkey, offset, userIdHash, 0, userIdHash.length );
        Bytes.putBytes( rowkey, offset, timestamp, 0, timestamp.length );

        return rowkey;

     * Extracts the date from a row key. Note that the user ID is hashed (one-way operation) so there is no way
     * to retrieve the user ID, but you can retrieve the date
     * @param rowkey        The row key from which to retrieve the time stamp
     * @return              The timestamp as a long
    public static long getTimestampFromRowKey( byte[] rowkey )
            // Extract the time stamp bytes
            byte[] timestampBytes = Bytes.copy(rowkey, 16, Long.SIZE / 8);

            // Convert the byte[] to a long
            ByteArrayInputStream bais = new ByteArrayInputStream(timestampBytes);
            DataInputStream dis = new DataInputStream(bais);
            return dis.readLong();
        catch( Exception e )

        // The operation failed
        return -1;

    public static void main( String[] args )

            // Create a configuration that connects to a local HBase
            Configuration conf = HBaseConfiguration.create();

            // Connect to the PageViews table
            HTableInterface pageViewTable = new HTable( conf, "PageViews" );

            // Insert 10,000 rows
            for( int i=0; i<10000; i++ )


                // Create a user ID for this user: the user ID will be User 0, User 1, ... User 99
                String userId = "User " + i%100;

                // Create a Put object for this row key
                Put put = new Put( generateRowKey( userId ) );

                // Add the user id to the info column family
                put.add( Bytes.toBytes( "info" ),
                        Bytes.toBytes( "userId" ),
                        Bytes.toBytes( userId ) );

                // Add the page to the info column family
                put.add( Bytes.toBytes( "info" ),
                        Bytes.toBytes( "page" ),
                        Bytes.toBytes( "/page/" + i%100 ) );

                // Add the PageView to the page view table
                pageViewTable.put( put );


            // Close the connection to the table

        catch (Exception e)

The main() method in Listing 1 connects to the PageViews table using a standard configuration (connect to the instance of HBase running on the local machine on the standard port) by creating an instance of the HTable class. We could have used a connection pool, but for this example we’re just going to connect, insert 10,000 rows, and disconnect. It creates a for loop that iterates 10,000 times and performs the following steps:

  1. Create a new user id as “User “ with the count of the current iteration mod-ed by 100; in other words, we’ll see values of “User 0” through “User 99”.
  2. Generates a row key for the user id (see below) and creates a new Put instance for that row key.
  3. Adds the userId and page columns to the Put instance’s info column family.
  4. Executes the Put.

Then it closes the HTable and exits.

The only challenge that we face in this example is the creation of the row key. For all intents and purposes, we can use whatever row key we would like, but I opted to use a row key that has meaning: MD5Hash of the user ID + the time stamp. This has meaning because HBase supports two types of analysis:

  • Table scans
  • MapReduce analysis

Table scans enable us to provide start and end keys and HBase will return all rows that are in between the two. This means that if we prefix the row key with a hash of the user id, we can pass in the user id with a timestamp of 0 and the user id plus 1 and we’ll retrieve all entries that match that user. In short, HBase can either perform offline analytics using MapReduce, or it can be used as a key-value store, but only if you choose your keys wisely!

The generateRowKey() method first creates an MD5 hash of the specified user id, using the java.security.MessageDigest class and then proceeds to generate a random date and time, in which the year is always 2014, but the month, day, and time are random. It converts the date time into milliseconds, which is returned as a long, and then it uses the HBase Bytes class to convert that into a byte array.

It creates a new byte array that is the length of the MD5 hash (16 bytes) and the length of a long (in bytes) and uses the Bytes class to put the MD5 hash into the beginning of the array and the timestamp into the end of the array.

Finally, I added another helper method that we’ll use later that extracts the timestamp from a row key and returns it as a long. The process is basically the reverse of what we did in the generateRowKey() method: Use the Bytes class to copy from byte 17 until the end of the row key into a new byte array and then convert the byte array into a long. You can find the source code to this article below, along with the Maven POM file with all the dependencies. When you’re ready, build and execute this class and make sure that you have your 10,000 records in HBase.

Now that we have data, let’s write a MapReduce application to analyze it. For this example we’re going to use HBase as a data source and we’ll write our data out to the file system. The analysis that we’ll be performing is calculating the number of views per hour of day over all the rows in the database. In other words, of the 10,000 page views that we’ve seen, how many of them were between 12:00 a.m. and 1:00 a.m., between 8:00 p.m. and 9:00 p.m., and so forth. The process is actually fairly straightforward:

  • Our mapper receives the row key as the key and a Result object that contains the columns (userId and page) as the value. It extracts the hour of day from the timestamp (from the row key) and emits the value: hour-of-day as the key and 1 as the value. (In other words, I just saw 1.)
  • Hadoop sorts all our hour-of-day/count emissions and invokes our reducer with the key being the hour-of-day and the results being a collection of counts of the number of times that hour-of-day has been seen by each mapper or combiner. In the simple case this is a collect of all “1”s, but if we were to employ a combiner that runs the reduction locally on each machine before it gets to us, then some of the values may not be 1.
  • Our reducer receives the hour-of-day and collection from Hadoop, iterates over the collection, and adds up the number of occurrences. It then emits the hour-of-day and its sum.

Listing 2 shows the source code for the MapReduceExample class.

Listing 2. MapReduceExample.java

package com.geekcap.informit.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;
import java.util.Calendar;

public class MapReduceExample

    public MapReduceExample() {


    static class MyMapper extends TableMapper<LongWritable, LongWritable>
        private LongWritable ONE = new LongWritable( 1 );

        public MyMapper() {

        protected void map( ImmutableBytesWritable rowkey, Result columns, Context context ) throws IOException, InterruptedException


            // Get the timestamp from the row key
            long timestamp = ExampleSetup.getTimestampFromRowKey(rowkey.get());

            // Get hour of day
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis( timestamp );
            int hourOfDay = calendar.get( Calendar.HOUR_OF_DAY );

            // Output the current hour of day and a count of 1
            context.write( new LongWritable( hourOfDay ), ONE );

    static class MyReducer extends Reducer<LongWritable, LongWritable, LongWritable, LongWritable>

        public MyReducer() {

        protected void reduce(LongWritable key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException

            // Add up all of the page views for this hour
            long sum = 0;
            for( LongWritable count : values )
                sum += count.get();

            // Write out the current hour and the sum
            context.write( key, new LongWritable( sum ) );

    public static void main( String[] args )
            // Setup Hadoop
            Configuration conf = HBaseConfiguration.create();
            Job job = Job.getInstance(conf, "PageViewCounts");
            job.setJarByClass( MapReduceExample.class );

            // Create a scan
            Scan scan = new Scan();

            // Configure the Map process to use HBase

                    "PageViews",                    // The name of the table
                    scan,                           // The scan to execute against the table
                    MyMapper.class,                 // The Mapper class
                    LongWritable.class,             // The Mapper output key class
                    LongWritable.class,             // The Mapper output value class
                    job );                          // The Hadoop job

            // Configure the reducer process
            job.setReducerClass( MyReducer.class );
            job.setCombinerClass( MyReducer.class );

            // Setup the output - we'll write to the file system: HOUR_OF_DAY   PAGE_VIEW_COUNT
            job.setOutputKeyClass( LongWritable.class );
            job.setOutputValueClass( LongWritable.class );
            job.setOutputFormatClass( TextOutputFormat.class );

            // We'll run just one reduce task, but we could run multiple
            job.setNumReduceTasks( 1 );

            // Write the results to a file in the output directory
            FileOutputFormat.setOutputPath( job, new Path( "output" ) );

            // Execute the job
            System.exit( job.waitForCompletion( true ) ? 0 : 1 );

        catch( Exception e )

The MapReduceExample class contains two inner classes:

  • MyMapper: Extends the TableMapper class, which is provided by HBase, and overrides the map() method. The TableMapper is parameterized with two LongWritables, which means that the MyMapper class emits keys of type LongWritable and values of type LongWritable. LongWritable is just a Hadoop wrapper around a Long instance that it can pass around from machine-to-machine. The map() method, which is inherited from TableMapper, receives the row key as an ImutableBytesWritable (HBase Hadoop wrapper around a byte array) and a Result instance that contains the request column families for this row (see below when we talk about the main() method). The mechanism that it uses to emit the hour-of-day to count-of-one is to execute the provided Context’s write() method, passing it the key and value wrapped in LongWritable wrappers.
  • MyReducer: Extends the Hadoop Reduce class and specifies four LongWriteables in its signature, which specifies the input key, the input value, the output key, and the output value, respectively. The reduce() method is passed the key as a LongWritable (hour-of-day) and the value as a collection of LongWritables. It iterates over the values, computes a sum, and then emits the result as the hour-of-day mapped to the sum, using the Context class’s write() method.

The main() method orchestrates the process by creating a Hadoop Job named “PageViewsCount”, a Scan that returns all rows in the PageViews table, and setting up the mapper and reducer. It leverages the TableMapReduceUtil class’ initTableMapperJob() method to set up the mapper. This method configures the Hadoop Job with the following information:

  • The name of the table to execute the scan against
  • The scan to execute
  • The mapper class that contains the map() method to which each result of the scan is passed
  • The class of the key that the mapper emits
  • The class of the value that the mapper emits
  • A reference to the job to configure

If we were using HBase as both a data source and a sink, then we would use the TableMapReduceUtil class’ initTableReducerJob() method to configure the reducer, but because we’re using only HBase as a data source, we can configure the reducer as we would in a normal Hadoop map reduce application. We set the reducer class and the combiner class both to MyReducer, which means that if we were running in a Hadoop cluster, Hadoop could perform local reductions (combiner) and then all reductions would ultimately be passed to the reducer. The reducer output key class and the reducer output value class are both set to be LongWritables and we set the number of reduce tasks to be 1. We configure a FileOutputFormat for the job that creates a new directory named output to store the results of the reduce job: This contains a set LongWritable keys with their associated LongWritable value.

Finally, the Job’s waitForCompletion() method is executed to start the map reduce application and run it to completion.

When the job completes, it creates a file in the output directory that is named something like “part-r-00000”. In my example I have the following output:

0    417
1    414
2    417
3    401
4    427
5    411
6    409
7    444
8    414
9    420
10    439
11    381
12    406
13    438
14    388
15    403
16    432
17    423
18    427
19    409
20    388
21    415
22    437
23    440

This shows that of the 10,000 page views, 417 occurred between 12 a.m. and 1 a.m., 414 occurred between 1 a.m. and 2 a.m., and so forth. Because we used the Random class, which uses a normal distribution across its range, the counts are relatively similar across all hours.

Listing 3 shows the contents of the POM file that I used to build this application.

Listing 3. 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">







To execute the MapReduce job, we need classes contained in the hbase-server library, so I included that dependency; make sure that your hbase-server version matches the version of your server. By defining a main class, you can execute the resultant JAR file to run the map reduce job:

java –jar hbase-example-1.0-SNAPSHOT.jar
  • + Share This
  • 🔖 Save To Your Account