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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020