MapReduce词频统计

自定义Mapper实现

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;

/**
 * KEYIN: Map任务读取数据的key类型,offset,是每行数据起始位置的偏移量,一般为Long类型
 * VALUEIN: Map任务读取数据的value类型,其实就是一行行的字符串,String
 *
 * KEYOUT: map方法自定义实现输出的key类型,String
 * VALUEOUT: map方法自定义实现输出的value类型,Integer
 *
 * 假设有如下待处理文本:
 * hello world world
 * hello welcome
 *
 * 词频统计:相同单词的次数 (word,1)
 *
 * Long,String,String,Integer是Java里面的数据类型
 * Hadoop自定义类型:支持序列化和反序列化
 *
 * LongWritable,Text,Text,IntWritable
 *
 */
public class WordCountMapper extends Mapper<LongWritable, Text,Text, IntWritable> {
    // 重写map方法
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // key是偏移量,value是一行行数据
        /**
         * Map任务的要求:
         *      (1)切割
         *      (2)赋1,转成key-value类型,写入context
         *      (3)其他的交给Shuffle和Reducer处理
         */
        String[] words = value.toString().split(" ");// 按指定分隔符切割
        for (String word : words) {
            context.write(new Text(word),new IntWritable(1)); // java类型转hadoop类型
            // (hello,1) (world,1) (world,1)
            // (hello,1) (welcome,1)
        }

    }
}

自定义Reducer实现

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.Iterator;

public class WordCountReducer extends Reducer<Text, IntWritable,Text, IntWritable> {
    // 重写reduce方法
    /** map的输出
     * (hello,1) (world,1) (world,1)
     * (hello,1) (welcome,1)
     *
     * map的输出到reduce端,是按照相同的key分发到一个reduce上执行
     * reduce1: (hello,1) (hello,1) ==> (hello,<1,1>)
     * reduce2: (world,1) (world,1) ==> (world,<1,1>)
     * reduce3: (welcome,1)         ==> (welcome,<1>)
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        /**
         * Reducer任务的要求:(因为每个reduce任务处理的是相同的一个单词的集合)
         * (1) 迭代value数组,累加求次数
         * (2) 取出key单词,拼成(key,次数),写入context
         */
        int count = 0;
        Iterator<IntWritable> its = values.iterator();
        while (its.hasNext()){
            IntWritable next = its.next();
            count += next.get(); //取值
        }
        // 写入context
        context.write(key,new IntWritable(count));
    }
}

编写Driver类

import org.apache.hadoop.conf.Configuration;
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 使用MR统计HDFS上文件的词频
 */
public class WordCountDriver {
    public static void main(String[] args) throws Exception{
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://localhost:9000");
        System.setProperty("HADOOP_USER_NAME","hadoop");
        // 创建一个Job
        Job job = Job.getInstance(conf);
        // 设置Job对应的参数
        job.setJarByClass(WordCountDriver.class); //主类
        job.setMapperClass(WordCountMapper.class); //使用的Mapper
        job.setReducerClass(WordCountReducer.class); //使用的Reducer
        // 设置Mapper,Reducer的输出类型
        job.setMapOutputKeyClass(Text.class);   //Mapper输出的key类型
        job.setMapOutputValueClass(IntWritable.class); //Mapper输出的value类型
        job.setOutputKeyClass(Text.class);   //Reducer输出的key类型
        job.setOutputValueClass(IntWritable.class);  //Reducer输出的value类型
        // 设置作业的输入输出路径
        FileInputFormat.setInputPaths(job,new Path("input"));
        FileOutputFormat.setOutputPath(job,new Path("output"));
        // 提交Job
        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : -1);
    }
}

本地测试开发

上面使用的都是基于HDFS的,那么如何使用本地呢?

import org.apache.hadoop.conf.Configuration;
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 使用MR统计本地文件的词频:
 * 使用本地文件进行词频统计,然后把统计结果输出到本地
 * 步骤:
 *      (1)不需要hdfs路径
 *      (2)不需要远程访问权限hadoop
 *      (3)在项目本地创建好input目录访问即可(input和src是同级目录!)
 */
public class WordCountLocalDriver {
    public static void main(String[] args) throws Exception{
        Configuration conf = new Configuration();
        // 创建一个Job
        Job job = Job.getInstance(conf);
        // 设置Job对应的参数
        job.setJarByClass(WordCountLocalDriver.class); //主类
        job.setMapperClass(WordCountMapper.class); //使用的Mapper
        job.setReducerClass(WordCountReducer.class); //使用的Reducer
        // 设置Mapper,Reducer的输出类型
        job.setMapOutputKeyClass(Text.class);   //Mapper输出的key类型
        job.setMapOutputValueClass(IntWritable.class); //Mapper输出的value类型
        job.setOutputKeyClass(Text.class);   //Reducer输出的key类型
        job.setOutputValueClass(IntWritable.class);  //Reducer输出的value类型
        // 设置作业的输入输出路径
        FileInputFormat.setInputPaths(job,new Path("input"));
        FileOutputFormat.setOutputPath(job,new Path("output"));
        // 提交Job
        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : -1);
    }
}

强烈建议

使用本地模式进行测试和开发,非常高效,Debug也很方便。

代码升级

  • 使用代码,删除HDFS的output目录
// 删除output目录
FileSystem fs = FileSystem.get(new URI("hdfs://localhost:9000"), conf, "hadoop");
Path outputPath = new Path("output");
if (fs.exists(outputPath)){
    fs.delete(outputPath,true);
}
  • map端聚合Combiner

处理逻辑和Reducer完全一模一样,直接套用即可!

// 设置Combiner
job.setCombinerClass(WordCountReducer.class);

使用Combiner优缺点

  • 优点

    能减少IO,提升作业的执行性能。

  • 缺点

    除法操作慎用!

猜你喜欢

转载自www.cnblogs.com/JZTX123/p/10647932.html