DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Migrate HDFS Data to Azure
  • All You Need to Know About Apache Spark
  • CubeFS: High-Performance Storage for Cloud-Native Apps
  • Hammerspace Empowers GPU Computing With Enhanced S3 Data Orchestration

Trending

  • Docker Base Images Demystified: A Practical Guide
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Building an AI/ML Data Lake With Apache Iceberg
  • Driving DevOps With Smart, Scalable Testing
  1. DZone
  2. Data Engineering
  3. Big Data
  4. Hadoop Basics—Creating a MapReduce Program

Hadoop Basics—Creating a MapReduce Program

The Map Reduce Framework works in two main phases to process the data, which are the "map" phase and the "reduce" phase.

By 
Carlo Scarioni user avatar
Carlo Scarioni
·
Mar. 18, 12 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
212.3K Views

Join the DZone community and get the full member experience.

Join For Free

Hadoop is an open source project for processing large datasets in parallel with the use of low level commodity machines.

Hadoop is built on two main parts: A special file system called Hadoop Distributed File System (HDFS) and the Map Reduce Framework.

The HDFS File System is an optimized file system for distributed processing of very large datasets on commodity hardware.

The Map Reduce Framework works in two main phases to process the data, which are the "map" phase and the "reduce" phase.

To explain this, let's create a sample Hadoop application.

Creating the Application

This application will take different translation dictionaries of English to other languages (English-Spanish, English-Italian, English-French) and create a dictionary file that has the English word followed by all the translations pipe-separated.

The first thing is, of course, downloading Hadoop. We go to the directory we want to install hadoop and download it wget http://apache.favoritelinks.net//hadoop/core/stable/hadoop-0.20.2.tar.gz. Then unzip it tar zxvf hadoop-0.21.0.tar.gz.

Now we get our dictionary files. I downloaded them from http://www.ilovelanguages.com/IDP/files/.txt

The next thing will be to put our files in HDFS (This example doesn’t really need to do this, but i’m doing it just to show how). For this we need first to format a filesystem to HDFS. This is done in the following way:

We go to the bin directory of hadoop and execute ./hadoop namenode -format. This will by default format the directory /tmp/hadoop-username/dfs/name.

After the system is formated we need to put our dictionary files into this filesystem. Hadoop works better with one large files than with many small ones. So we'll merge the files into one to put them there.

Although this should better be done while writing to the hadoop file system using a PutMerge operation, we are merging the files first and then copying them to hdfs which is easier and our example files are small.

cat French.txt >> fulldictionary.txt

cat Italian.txt >> fulldictionary.txt

cat Spanish.txt >> fulldictionary.txt

To copy the file to hdfs we execute the following command:

./hadoop fs -put /home/cscarioni/Documentos/hadooparticlestuff/fulldictionary.txt /tmp/hadoop-cscarioni/dfs/name/file

We will now create the actual map reduce program to process the data. The program will be completely contained in one unique Java file. In the file we will have the Map and the Reduce algorithms. Let's see the code and then explain how the map reduce framework works.

import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class Dictionary
{
    public static class WordMapper extends Mapper<Text, Text, Text, Text>
    {
        private Text word = new Text();
        public void map(Text key, Text value, Context context) throws IOException, InterruptedException
        {
            StringTokenizer itr = new StringTokenizer(value.toString(),",");
            while (itr.hasMoreTokens())
            {
                word.set(itr.nextToken());
                context.write(key, word);
            }
        }
    }
    public static class AllTranslationsReducer
    extends Reducer<Text,Text,Text,Text>
    {
        private Text result = new Text();
        public void reduce(Text key, Iterable<Text> values,
        Context context
        ) throws IOException, InterruptedException
        {
            String translations = "";
            for (Text val : values)
            {
                translations += "|"+val.toString();
            }
            result.set(translations);
            context.write(key, result);
        }
    }
    public static void main(String[] args) throws Exception
    {
        Configuration conf = new Configuration();
        Job job = new Job(conf, "dictionary");
        job.setJarByClass(Dictionary.class);
        job.setMapperClass(WordMapper.class);
        job.setReducerClass(AllTranslationsReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setInputFormatClass(KeyValueTextInputFormat.class);
        FileInputFormat.addInputPath(job, new Path("/tmp/hadoop-cscarioni/dfs/name/file"));
        FileOutputFormat.setOutputPath(job, new Path("output"));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

Watching at the code we can see that our class is built basically of three parts. A static class holds the mapper, other static class holds the reducer, and the main method works as the driver of our application. Follow along with the code as you read the next few paragraphs.

First, Let’s Talk About the Mapper

Our mapper is a very standard mapper. A mapper’s main work is to produce a list of key value pairs to be processed later. The ideal structure of this list of key value pairs is so that the keys will be repeated in many elements of the list (produced by this same mapper or another one that will combine it’s results with this one) so the next phases of the map reduce algorithm make use of them. A mapper receives a key, value pair as parameters, and as said, produce a list of new key, value pairs.

The key value pair received by the mapper depends on the InputFormat implementation used. In our example we are using KeyValueTextInputFormat. This implementation uses as each key value pair, the begining of each line of the input file until the first space as the key, and the rest of the line as the value. So if a line contains aaa bbb,ccc,ddd we’ll get aaa as the key and bbb,ccc,ddd as the value.

From each input to the mapper, the generated list of key value pairs is the key combined with each of the values separated by comma. explaining: For the input aaa bbb,ccc,ddd the output will be: List(aaa bbb, aaa ccc, aaa ddd) and that for each input to the mapper.

The Reducer

After the mapper, and before the reducer, the shuffler and combining phases take place. The shuffler phase assures that every key value pair with the same key goes to the same reducer, the combining part converts all the key value pairs of the same key to the grouping form key,list(values), which is what the reducer ultimately receives.

The more standard reducer’s job is to take the key list(values) pair, operate on the grouped values, and store it somewhere. That is exactly what our reducer does. It takes the key list(values) pair, loop through the values concatenating them to a pipe-separated string, and send the new key value pair to the output, so the pair aaa list(aaa,bbb) is converted to aaa aaa|bbb and stored out.

To run our program simply run it as a normal java main file with hadoop libs on the classpath (all the jars in the hadoop home directory and all the jars in the hadoop lib directory. you can also run the hadoop command with the classpath option to get the full classpath needed). For this first test i used the IDE DrJava.

Running the program in my case generated a file called part-r-00000 with the expected result.

Distributing It

Map Reduce Framework's main reason of existence is to run the processing of large ammounts of data in a distributed manner, in commodity machines. In fact running it on only one machine doesn’t have much more utility than teaching us how it works.

Distributing the application can be the subject of another more advanced post.

hadoop File system MapReduce

Published at DZone with permission of Carlo Scarioni, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Migrate HDFS Data to Azure
  • All You Need to Know About Apache Spark
  • CubeFS: High-Performance Storage for Cloud-Native Apps
  • Hammerspace Empowers GPU Computing With Enhanced S3 Data Orchestration

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!