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

  • 缺点

    除法操作慎用!

原文地址:https://www.cnblogs.com/JZTX123/p/10647932.html

时间: 2024-08-30 05:23:23

MapReduce词频统计的相关文章

实验二-3 Hadoop&amp;Paoding 中文词频统计

  参考教程 在Hadoop上使用庖丁解牛(较复杂,并未采用,可以之后试试) http://zhaolinjnu.blog.sohu.com/264905210.html Lucene3.3.Lucene3.4中文分词——庖丁解牛分词实例(屈:注意版本) http://www.360doc.com/content/13/0217/13/11619026_266124504.shtml 庖丁分词在hadoop上运行时的配置问题(采纳了一半,没有按照其所写配置dic属性文件) http://f.da

初学Hadoop之中文词频统计

1.安装eclipse 准备 eclipse-dsl-luna-SR2-linux-gtk-x86_64.tar.gz 安装 1.解压文件. 2.创建图标. ln -s /opt/eclipse/eclipse /usr/bin/eclipse #使符号链接目录 vim /usr/share/applications/eclipse.desktop #创建一个  Gnome 启动 添加如下代码: [Desktop Entry] Encoding=UTF-8 Name=Eclipse 4.4.2

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

声明: 1)本文由我bitpeach原创撰写,转载时请注明出处,侵权必究. 2)本小实验工作环境为Windows系统下的百度云(联网),和Ubuntu系统的hadoop1-2-1(自己提前配好).如不清楚配置可看<Hadoop之词频统计小实验初步配置> 3)本文由于过长,无法一次性上传.其相邻相关的博文,可参见<Hadoop的改进实验(中文分词词频统计及英文词频统计) 博文目录结构>,以阅览其余三篇剩余内容文档. (五)单机伪分布的英文词频统计Python&Streamin

hadoop中文分词、词频统计及排序

需求如下: 有如图所示的输入文件.其中第一列代表ip地址,之后的偶数列代表搜索词,数字(奇数列)代表搜索次数,使用"\t"分隔.现在需要对搜索词进行分词并统计词频,此处不考虑搜索次数,可能是翻页,亦不考虑搜索链接的行为. 这里中文分词使用了IK分词包,直接将源码放入src中.感谢IK分词. 程序如下: <span style="font-size:14px;">package seg; import java.io.ByteArrayInputStrea

Hadoop基础学习(一)分析、编写并运行WordCount词频统计程序

前面已经在我的Ubuntu单机上面搭建好了伪分布模式的HBase环境,其中包括了Hadoop的运行环境. 详见我的这篇博文:http://blog.csdn.net/jiyiqinlovexx/article/details/29208703 我的目的主要是学习HBase,下一步打算学习的是将HBase作为Hadoop作业的输入和输出. 但是好像以前在南大上学时学习的Hadoop都忘记得差不多了,所以找到以前上课做的几个实验:wordCount,PageRank以及InversedIndex.

Hadoop之词频统计小实验(基于单节点伪分布)

声明:1)本文由我bitpeach原创撰写,转载时请注明出处,侵权必究. 2)本小实验工作环境为Ubuntu操作系统,hadoop1-2-1,jdk1.8.0. 3)统计词频工作在单节点的伪分布上,至于真正实际集群的配置操作还没有达到,希望能够由本文抛砖引玉. (一)Hadoop的配置修正 网上有很多Hadoop的配置教程,可自行寻找,这一部分主要是根据自身实际情况,结合自身特点,设置Hadoop.因为有时候根据别人的教程,设置总是不成功,因为别人的教程依赖于别人的软件或操作环境特点. 本部分也

Java实现的一个词频统计程序

import java.util.HashMap; import java.util.Iterator; public class WordCount { public static void main(String[] args) { String[] text=new String[]{"the weather is good ","today is good","today has good weather","good weat

hive进行词频统计

统计文件信息: $ /opt/cdh-5.3.6/hadoop-2.5.0/bin/hdfs dfs -text /user/hadoop/wordcount/input/wc.input hadoop spark spark hadoop oracle mysql postgresql postgresql oracle mysql mysql mongodb hdfs yarn mapreduce yarn hdfs zookeeper 针对于以上文件使用hive做词频统计: create

大数据基础之词频统计Word Count

对文件进行词频统计,是一个大数据领域的hello word级别的应用,来看下实现有多简单: 1 Linux单机处理 egrep -o "\b[[:alpha:]]+\b" test_word.log|sort|uniq -c|sort -rn|head -10 2 Spark分布式处理(Scala优雅简洁) val sparkConf = new SparkConf() val sc = new SparkContext(sparkConf) sc.textFile("tes