自定义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,提升作业的执行性能。

  • 缺点

    除法操作慎用!

MapReduce词频统计的更多相关文章

  1. MapReduce实现词频统计

    问题描述:现在有n个文本文件,使用MapReduce的方法实现词频统计. 附上统计词频的关键代码,首先是一个通用的MapReduce模块: class MapReduce: __doc__ = ''' ...

  2. Hadoop上的中文分词与词频统计实践 (有待学习 http://www.cnblogs.com/jiejue/archive/2012/12/16/2820788.html)

    解决问题的方案 Hadoop上的中文分词与词频统计实践 首先来推荐相关材料:http://xiaoxia.org/2011/12/18/map-reduce-program-of-rmm-word-c ...

  3. 【原创】大数据基础之词频统计Word Count

    对文件进行词频统计,是一个大数据领域的hello word级别的应用,来看下实现有多简单: 1 Linux单机处理 egrep -o "\b[[:alpha:]]+\b" test ...

  4. Hive简单编程实践-词频统计

    一.使用MapReduce的方式进行词频统计 (1)在HDFS用户目录下创建input文件夹 hdfs dfs -mkdir input 注意:林子雨老师的博客(http://dblab.xmu.ed ...

  5. hive进行词频统计

    统计文件信息: $ /opt/cdh-5.3.6/hadoop-2.5.0/bin/hdfs dfs -text /user/hadoop/wordcount/input/wc.input hadoo ...

  6. Hadoop的改进实验(中文分词词频统计及英文词频统计)(4/4)

    声明: 1)本文由我bitpeach原创撰写,转载时请注明出处,侵权必究. 2)本小实验工作环境为Windows系统下的百度云(联网),和Ubuntu系统的hadoop1-2-1(自己提前配好).如不 ...

  7. 初学Hadoop之中文词频统计

    1.安装eclipse 准备 eclipse-dsl-luna-SR2-linux-gtk-x86_64.tar.gz 安装 1.解压文件. 2.创建图标. ln -s /opt/eclipse/ec ...

  8. 初学Hadoop之WordCount词频统计

    1.WordCount源码 将源码文件WordCount.java放到Hadoop2.6.0文件夹中. import java.io.IOException; import java.util.Str ...

  9. Hadoop之词频统计小实验

    声明:    1)本文由我原创撰写,转载时请注明出处,侵权必究. 2)本小实验工作环境为Ubuntu操作系统,hadoop1-2-1,jdk1.8.0. 3)统计词频工作在单节点的伪分布上,至于真正实 ...

随机推荐

  1. 洛谷P5119 Convent 题解

    题目 很好想的一道二分题,首先,二分一定满足单调性,而题目中非常明显的就是用的车越多,所用时间越少,所以可以枚举时间,判断是否可以比\(m\)少. 然后在二分时,更是要注意下标的一些问题,也要注意车和 ...

  2. python多线程中join()方法和setDaemon()方法的区别

    """ join()方法:主线程A中,创建了子线程B,并且在主线程中调用了B.join()方法,那么主线程A会在调用的地方等待,直到子线程B完成操作后,才可以接着往下执行 ...

  3. ZOJ 3949 Edge to the Root( 树形dp)

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3949 题解:树dp真的很直觉,或者说dp真的很直觉.就上周末比赛时其实前一 ...

  4. 为什么天线的回波损耗以-10dB大小来衡量?

    传送门:http://www.eeworld.com.cn/Test_and_measurement/2014/0610/article_9152.html i:对于2端口无损耗网络,可以根据S11的 ...

  5. Linux 三剑客(Awk、Sed、Grep)

    grep/egrep 主要作用:给搜索过滤出来的内容加上颜色和排除功能 常用参数 -V 打印grep的版本号 -E 解释PATTERN作为扩展正则表达式,也就相当于使用egrep. 或操作 -F 解释 ...

  6. 史上最全PMP备考考点全攻略(上篇-五大过程组,附赠资料)

    一.这可能是一篇史上最全的PMP备考考点全梳理文章 写在前面,这可能是史上最全的PMBOK考点全书考点梳理,由PMP备考自律营呕心沥血整理,内容较长,分为上下篇,绝对值得所有正在备考PMP的学员收藏! ...

  7. GWAS后续分析:LocusZoom图的绘制

    LocusZoom图几乎是GWAS文章的必备图形之一,其主要作用是可以快速可视化GWAS找出来的信号在基因组的具体信息:比如周围有没有高度连锁的位点,高度连锁的位点是否也显著. 下面是locuszoo ...

  8. webpack优化

    注:总结自吴浩麟---<webpack深入浅出>第四章--优化 1.缩小文件的搜索范围 1.1 优化loader:module.rules中,使用test,include,exclude尽 ...

  9. C++: 模板函数定义与声明分离;

    我们知道模板函数或模板类的定义一般都是和声明一起在头文件中,但是这样的话, 就暴露了内部实现,有什么办法能够将定义和声明进行分离呢? 答案是: 有的: 头文件: test.h; class test ...

  10. python静态属性的理解

    python中并没有像 C语言 C++ java 那样定义静态属性的关键字 static 那么在python中是怎么做的呢? class A(object): name="lance&quo ...