Skip to content

Instantly share code, notes, and snippets.

@amygdala
Created October 2, 2009 23:09
Show Gist options
  • Save amygdala/200226 to your computer and use it in GitHub Desktop.
Save amygdala/200226 to your computer and use it in GitHub Desktop.
package com.inferdata.hadoop;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
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 Exception {
Configuration cnf = new Configuration();
cnf.set("delims", " \t\r\n.,()[]{}+-*/=;:");
Job conf = new Job(cnf, "word count");
conf.setJarByClass(Driver.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(LongWritable.class);
FileInputFormat.addInputPath(conf, new Path("input"));
FileOutputFormat.setOutputPath(conf, new Path("output"));
conf.setMapperClass(WordCountMapper.class);
conf.setReducerClass(SumReducer.class);
try {
System.exit(conf.waitForCompletion(true) ? 0 : 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.inferdata.hadoop;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.io.Text;
public class SumReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
public void reduce(Text key, Iterable<LongWritable> values,
Context context
) throws IOException, InterruptedException {
LongWritable result = new LongWritable();
long sum = 0;
for (LongWritable val : values) {
sum += val.get();
}
// output sum
result.set(sum);
context.write(key, result);
}
}
package com.inferdata.hadoop;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.mapreduce.Mapper;
public class WordCountMapper extends Mapper<Object, Text, Text, LongWritable>{
String delims;
protected void setup(Mapper<Object, Text, Text, LongWritable>.Context context) {
Configuration cnf = context.getConfiguration();
delims = cnf.get("delims");
// System.out.println("delims are: " + delims);
}
public void map(Object key, Text value,
Context context) throws IOException, InterruptedException
{
String text = value.toString();
StringTokenizer tokenizer = new StringTokenizer(text, delims);
// StringTokenizer tokenizer = new StringTokenizer(text, " \t\r\n.,()[]{}+-*/=;:");
Text word = new Text ();
LongWritable one = new LongWritable(1);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment