Monday, April 27, 2015

WordCount MapReduce Programme

import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.examples.WordCount.IntSumReducer;
import org.apache.hadoop.examples.WordCount.TokenizerMapper;
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 WordCountNew {


 // mapper class
 public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>
 {
  private static final IntWritable one=new IntWritable(1);
  private Text word=new Text();
  public void map(Object key,Text value,Context cont) throws IOException, InterruptedException
  {
   StringTokenizer itr=new StringTokenizer(value.toString());
   while(itr.hasMoreTokens())
   {
    word.set(itr.nextToken());
    cont.write(word, one);
   }
  }
 }

 //Reducer Class
 public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable>
 {
 private IntWritable result=new IntWritable();
 public void reduce(Text key,Iterable<IntWritable> values,Context cont) throws IOException, InterruptedException
   {
    int sum=0;
    for(IntWritable val: values)
    {
     sum+=val.get();
    }
    result.set(sum);
    cont.write(key, result);
   }
 }


 public static void main(String[] args) throws Exception
 {

  //Configuration for Job,jar

  Configuration conf=new Configuration();
  Job j=new Job(conf,"Batch48S-Wordcount");
  j.setJarByClass(WordCountNew.class);

  // mapper,reducer,combiner class

  j.setMapperClass(TokenizerMapper.class);
  j.setCombinerClass(IntSumReducer.class);
  j.setReducerClass(IntSumReducer.class);

  //Output key, Value, data type details
  j.setOutputKeyClass(Text.class);
  j.setOutputValueClass(IntWritable.class);

  // Hdfs input and output path

  FileInputFormat.addInputPath(j,new Path(args[0]));
  FileOutputFormat.setOutputPath(j,new Path(args[1]));
  //execution

  System.exit(j.waitForCompletion(true)?0:1);
 }

}

No comments:

Post a Comment