hadoop 单词筛选 top-k问题

      最近开始学习hadoop(hadoop 以下简称hd),在完成了hd的环境搭建之后,就开始试着跑那些原始例子,比如其中的wordcount,统计文章中各单词的出现频率。由于本人还在念书,在我们这学期开设的软件工程课上,老师布置了一道题。如下:

    请实现程序:筛选出文章中出现频率最高的10个词语。文件大小30k--300k.

    一看这题,我立马想到了hd去实现,这300k的数据简直不够塞牙缝,由于本人是新手,就在网上找资料,不料,都没有能完全满足要求的代码。但是本人发现了解决topK问题的方法。并且通过编程,和娄哥的帮助,实现了top10问题,以此与众新手分享。

    ps:本程序是在wordcount基础上修改的,并且用的是hd的老mapreduce框架。(mapreduce以下简称mapred)

    大致思想是将多个mapred连接起来,将复杂任务分解成一些简单的子任务,每个均需通过单独的mapred作业来完成。

    首先,按照mapred框架,在第一次完成mapred之后,每个单词出现的频率会被统计,并且成 键值对(key/value)形式(单词 /次数),reduce之后,单词会成升序进行排序。

    由于mapred只会对键进行排序,所以我们下一步需要将键值互换位置,此时需要用到hd提供的api函数,InverseMapper.class

然后就会让单词按照出现次数升序排序,由于我们需要的是降序排序,所以需要实现一个降序排序的类(ps:此处参考了其他高手的解决方案IntWritableDecreasingComparator 

最后,再使用一个自定义map类,进行top-k的选取。

附上完整代码

package a;  

import java.io.IOException;  

import java.util.Random;  

import java.util.StringTokenizer;  

 

import org.apache.hadoop.conf.Configuration;  

import org.apache.hadoop.fs.FileSystem;  

import org.apache.hadoop.fs.Path;  

import org.apache.hadoop.io.IntWritable;  

import org.apache.hadoop.io.Text;  

import org.apache.hadoop.io.WritableComparable;  

import org.apache.hadoop.mapreduce.Job;  

import org.apache.hadoop.mapreduce.Mapper;  

import org.apache.hadoop.mapreduce.Reducer;  

import org.apache.hadoop.mapreduce.Mapper.Context;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  

import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;  

import org.apache.hadoop.mapreduce.lib.map.InverseMapper;  

import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  

import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;  

import org.apache.hadoop.util.GenericOptionsParser;  

public class WordCount2 {  

    public static class TokenizerMapper extends  

            Mapper {  

        private final static IntWritable one = new IntWritable(1);  

        private Text word = new Text();  

        public void map(Object key, Text value, Context context)  

                throws IOException, InterruptedException {  

            String line = value.toString().toLowerCase(); // 全部转换为小写字母

          StringTokenizer itr = new StringTokenizer(line, " \t\n\f\" . , : ; ? ! [ ] ' - ");

            while (itr.hasMoreTokens()) {  

                word.set(itr.nextToken());  

                context.write(word, one);  

            }  

        }  

    }  

    //top-k  maper

    public static class TokenizerMapper2 

    extends Mapper{

     int c=0;

      public void map(Object key, Text value, Context context

                      ) throws IOException, InterruptedException {

        StringTokenizer itr = new StringTokenizer(value.toString());

        IntWritable a=new IntWritable(Integer.parseInt(itr.nextToken()));

        Text b=new Text(itr.nextToken());

        if(c<10){

         System.out.println("sss");

          context.write(a, b);

          c++;

        }

      }

     }

    public static class IntSumReducer extends  

            Reducer {  

        private IntWritable result = new IntWritable();  

        public void reduce(Text key, Iterable values,  

                Context context) throws IOException, InterruptedException {  

            int sum = 0;  

            for (IntWritable val : values) {  

                sum += val.get();  

            }  

            result.set(sum);  

            context.write(key, result);  

        }  

    }  

      

     private static class IntWritableDecreasingComparator extends IntWritable.Comparator {  

          public int compare(WritableComparable a, WritableComparable b) { 

           System.out.println("ss");

            return -super.compare(a, b);  

          }  

            

          public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {  

           System.out.println("ss1");

              return -super.compare(b1, s1, l1, b2, s2, l2);  

          }  

      }  

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

        Configuration conf = new Configuration();  

        String[] otherArgs = new GenericOptionsParser(conf, args)  

                .getRemainingArgs();  

        if (otherArgs.length != 2) {  

            System.err.println("Usage: wordcount  ");  

            System.exit(2);  

        }  

         Path tempDir = new Path("wordcount-temp-" + Integer.toString(  

                    new Random().nextInt(Integer.MAX_VALUE))); //临时目录

         Path tempDir2 = new Path("wordcount-temp2-" + Integer.toString(  

                 new Random().nextInt(Integer.MAX_VALUE))); //

          

        Job job = new Job(conf, "word count");  

        job.setJarByClass(WordCount2.class);  

        try{  

            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(otherArgs[0]));  

            FileOutputFormat.setOutputPath(job, tempDir);//先将词频统计任务的输出结果写到临时下一个排序任务以临时目录为输入目录。

            job.setOutputFormatClass(SequenceFileOutputFormat.class);  

            if(job.waitForCompletion(true))  

            {  

                Job sortJob = new Job(conf, "sort");  

                sortJob.setJarByClass(WordCount2.class);  

                  

                FileInputFormat.addInputPath(sortJob, tempDir);  

                sortJob.setInputFormatClass(SequenceFileInputFormat.class);  

                  

                /*InverseMapper由hadoop库提供,作用是实现map()之后的数据对的key和value交换*/ 

                sortJob.setMapperClass(InverseMapper.class);  

                /*将 Reducer 的个数限定为1, 最终输出的结果文件就是一个。*/

                sortJob.setNumReduceTasks(1);   

                FileOutputFormat.setOutputPath(sortJob, tempDir2);  

                  

                sortJob.setOutputKeyClass(IntWritable.class);  

                sortJob.setOutputValueClass(Text.class);  

                /*Hadoop 默认对 IntWritable 按升序排序,而我们需要的是按降序排列。 

                 * 因此我们实现了一个 IntWritableDecreasingComparator 类,  

                 * 并指定使用这个自定义的 Comparator 类对输出结果中的 key (词频)进行排序*/

                sortJob.setSortComparatorClass(IntWritableDecreasingComparator.class);  

                if(sortJob.waitForCompletion(true))

                {

                 Job topJob = new Job(conf, "sort");  

                 topJob.setJarByClass(WordCount2.class);  

                      

                    FileInputFormat.addInputPath(topJob, tempDir2);  

                    //topJob.setInputFormatClass(SequenceFileInputFormat.class);  

                    topJob.setMapperClass(TokenizerMapper2.class);  

                    FileOutputFormat.setOutputPath(topJob, new Path(otherArgs[1]));  

                      

                    topJob.setOutputKeyClass(IntWritable.class);  

                    topJob.setOutputValueClass(Text.class);  

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

                }

                

       

               // System.exit(sortJob.waitForCompletion(true) ? 0 : 1);  

            }  

        }finally{  

            FileSystem.get(conf).deleteOnExit(tempDir);  

        }  

    }  

}

    

 注:参考博客:http://blog.csdn.net/xw13106209/article/details/6122719


    

你可能感兴趣的:(hadoop 单词筛选 top-k问题)