Basic Map Reduce Program in Java

We need 3 classes for Map Reduce Program. This program will simply read lines from file and write back in output file.

  1. Driver or Loader
  2. Mapper
  3. Reducer

 

Driver

package com.first.mr;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class Driver
{
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{

Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(Driver.class);
FileInputFormat.addInputPath(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setMapperClass(FirstMapper.class);
job.setReducerClass(FirstReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.waitForCompletion(true);
}
}

——X—–End of Driver—–X——

Mapper

package com.first.mr;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class FirstMapper extends Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context)
{
try {
context.write(new Text(key.toString()), value);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

——X—–End of Mapper—–X——

Reducer

package com.first.mr;

import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class FirstReducer extends Reducer<Text, Text, Text, Text> {
public void reducer(Text key, Iterable<Text> values, Context context) {
for(Text t: values){
try {
context.write(key, t);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

——X—–End of Reduce—–X——

Command

hadoop jar FirstMR-0.0.1-SNAPSHOT.jar com.first.mr.Driver <path of input file on hdfs> <path of output folder on hdfs>

Advertisements