Skip to content

Instantly share code, notes, and snippets.

@nvasilakis
Created December 12, 2014 02:13
Show Gist options
  • Save nvasilakis/af46e3a4d8c252f23aef to your computer and use it in GitHub Desktop.
Save nvasilakis/af46e3a4d8c252f23aef to your computer and use it in GitHub Desktop.
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.output.FileOutputFormat;
public class WordCount {
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
/*
* Mapper: takes lines of text, breaks them down into lowercase words and
* emits a (key,value) pair for each word, key being the word and
* value being `1`. For example, `one two two three three three` will emit:
* (one, 1)
* (two, 1)
* (two, 1)
*/
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken().toLowerCase());
context.write(word, one);
}
}
}
public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
/*
* Reducer: takes a word (key) and a list of int's (`1`'s) and returns
* a pair of (word, sum), with sum being the sum of all the list's values
* -- hence, the frequency. For example, (`two`, [1,1]) from above will emit
* (`two`, 2)
*/
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
/*
* Main driver: Creates a hadoop job, configures mapper, reducer,
* output types, files for input and output and
* runs the task.
*/
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
// job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.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