Last active
December 26, 2015 21:08
-
-
Save soren/7213453 to your computer and use it in GitHub Desktop.
A Hadoop Word Count example using my own map and reduce classes.
Tested with Java 1.6 and Hadoop 1.0.4.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
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.output.FileOutputFormat; | |
public class MyWordCount { | |
public static class MyWordCountMapper extends Mapper<Object, Text, Text, IntWritable> { | |
private final static IntWritable one = new IntWritable(1); | |
private Text word = new Text(); | |
public void map(Object key, Text value, Context context) throws IOException, InterruptedException { | |
for (String str : value.toString().toLowerCase().split("[\\W\\s]+")) { | |
word.set(str); | |
context.write(word, one); | |
} | |
} | |
} | |
public static class MyWordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { | |
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { | |
int total = 0; | |
for (IntWritable val : values) total += val.get(); | |
context.write(key, new IntWritable(total)); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
Job job = new Job(new Configuration(), "My Word Count"); | |
job.setJarByClass(MyWordCount.class); | |
job.setMapperClass(MyWordCountMapper.class); | |
job.setCombinerClass(MyWordCountReducer.class); | |
job.setReducerClass(MyWordCountReducer.class); | |
job.setOutputKeyClass(Text.class); | |
job.setOutputValueClass(IntWritable.class); | |
FileInputFormat.addInputPath(job, new Path(args[0])); | |
FileOutputFormat.setOutputPath(job, new Path(args[1])); | |
System.exit(job.waitForCompletion(true) ? 0 : 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment