Skip to content

Instantly share code, notes, and snippets.

@jblomo
Created March 23, 2012 17:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jblomo/2173199 to your computer and use it in GitHub Desktop.
Save jblomo/2173199 to your computer and use it in GitHub Desktop.
Hadoop MR JSON example
import java.io.IOException;
import java.util.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;
public class WordCount {
public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
private ObjectMapper mapper = new ObjectMapper();
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
String line = value.toString();
java.util.Map<String,String> rootAsMap = mapper.readValue(line, java.util.Map.class);
StringTokenizer tokenizer = new StringTokenizer(rootAsMap.get("text"));
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
output.collect(word, one);
}
}
}
public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
int sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
JobConf conf = new JobConf(WordCount.class);
conf.setJobName("wordcount");
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(IntWritable.class);
conf.setMapperClass(Map.class);
conf.setCombinerClass(Reduce.class);
conf.setReducerClass(Reduce.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
/* Deprecated ?
* conf.setInputPath(new Path(args[0]));
* conf.setOutputPath(new Path(args[1]));
*/
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
}
}
@jblomo
Copy link
Author

jblomo commented Mar 23, 2012

wget http://apache.mirrors.hoobly.com//hadoop/common/hadoop-0.20.205.0/hadoop-0.20.205.0.tar.gz
export HADOOP_CP=hadoop-ant-0.20.205.0.jar:hadoop-core-0.20.205.0.jar:hadoop-examples-0.20.205.0.jar:hadoop-test-0.20.205.0.jar:hadoop-tools-0.20.205.0.jar:lib/jackson-mapper-asl-1.0.1.jar:lib/jackson-core-asl-1.0.1.jar
javac -cp $HADOOP_CP -d wordcount_classes WordCount.java
jar -cvf wordcount.jar -C wordcount_classes .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment