- Back to Home »
- WordCount Example
Posted by : Sushanth
Thursday, 24 December 2015
Example 1: Word count
Input: orange mango banana
orange mango banana
orange mango banana
orange mango banana
Program:
package mypackage;
import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
public class wordcount_hadoop {
public static class Map extends MapReduceBase implements
Mapper<LongWritable, Text, Text, IntWritable> {
@Override
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
value.set(tokenizer.nextToken());
output.collect(value, new IntWritable(1));
}
}
}
public static class Reduce extends MapReduceBase implements
Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterator<IntWritable> values,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
int sum = 0;
while (values.hasNext()) {
sum = sum + values.next().get();
}
output.collect(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
JobConf newconf = new JobConf(wordcount_hadoop.class);
newconf.setJobName("wordcount_hadoop");
newconf.setOutputKeyClass(Text.class);
newconf.setOutputValueClass(IntWritable.class);
newconf.setMapperClass(Map.class);
newconf.setReducerClass(Reduce.class);
//newconf.setCombinerClass(Reduce.class);
newconf.setInputFormat(TextInputFormat.class);
newconf.setOutputFormat(TextOutputFormat.class);
FileInputFormat.setInputPaths(newconf, new Path(args[0]));
FileOutputFormat.setOutputPath(newconf, new Path(args[1]));
JobClient.runJob(newconf);
}
}
Output:
Orange – 4
Mango – 4
Banana – 4
How to run in cluster:
Start the cluster and make sure datanode,namenode,secondarynamenode,jobtracker and tasktracker running.
Move the input file from local file system to HDFS
Hadoop dfs –copyFromLocal <local_path> <HDFS_path>
Run map/reduce program
Hadoop jar <jar input path> <hadoop output path>