需求

  计算出文件中每个单词的频数。要求输出结果按照单词的字母顺序进行排序。每个单词和其频数占一行,单词和频数之间有间隔。

  比如,输入两个文件,其一内容如下:

  hello world

  hello hadoop

  hello mapreduce

  另一内容如下:

  bye world

  bye hadoop

  bye mapreduce

  对应上面给出的输入样例,其输出样例为:

  bye        3

  hadoop    2

  hello      3

  mapreduce   2

  world     2

方案制定

  对该案例,可设计出如下的MapReduce方案:

  1. Map阶段各节点完成由输入数据到单词切分再到单词搜集的工作

  2. shuffle阶段完成相同单词的聚集再到分发到各个Reduce节点的工作 (shuffle阶段是MapReduce的默认过程)

  3. Reduce阶段负责接收所有单词并计算各自频数

代码示例

 /**
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
  *  You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */

 package org.apache.hadoop.examples;

 import java.io.IOException;
 import java.util.StringTokenizer;

 //导入各种Hadoop包
 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.Mapper;
 import org.apache.hadoop.mapreduce.Reducer;
 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
 import org.apache.hadoop.util.GenericOptionsParser;

 // 主类
 public class WordCount {

     // Mapper类
     public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{

         // new一个值为1的整数对象
         private final static IntWritable one = new IntWritable(1);
         // new一个空的Text对象
         private Text word = new Text();

         // 实现map函数
         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {

             // 创建value的字符串迭代器
             StringTokenizer itr = new StringTokenizer(value.toString());

             // 对数据进行再次分割并输出map结果。初始格式为<字节偏移量,单词> 目标格式为<单词,频率>
             while (itr.hasMoreTokens()) {
                     word.set(itr.nextToken());
                     context.write(word, one);
             }
         }
     }

     // Reducer类
     public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {

         // new一个值为空的整数对象
         private IntWritable result = new IntWritable();

         // 实现reduce函数
         public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

             int sum = 0;
             for (IntWritable val : values) {
                 sum += val.get();
             }

             // 得到本次计算的单词的频数
             result.set(sum);

             // 输出reduce结果
             context.write(key, result);
         }
     }

     // 主函数
     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 <in> <out>");
                 System.exit(2);
         }

         // 定义作业对象
         Job job = new Job(conf, "word count");
         // 注册分布式类
         job.setJarByClass(WordCount.class);
         // 注册Mapper类
         job.setMapperClass(TokenizerMapper.class);
         // 注册合并类
         job.setCombinerClass(IntSumReducer.class);
         // 注册Reducer类
         job.setReducerClass(IntSumReducer.class);
         // 注册输出格式类
         job.setOutputKeyClass(Text.class);
         job.setOutputValueClass(IntWritable.class);
         // 设置输入输出路径
         FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
         FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));

         // 运行程序
         System.exit(job.waitForCompletion(true) ? 0 : 1);
     }
 }

运行方法

  1. 打开Eclipse并启动Hdfs (方法请参考前文)

  2. 新建一个MapReduce工程:”file" -> "new" -> "project",然后选择 "Map/Reduce Project"

  

  3. 设置输入目录及文件

  在项目工程包里面新建一个名为input的目录,里面存放需要处理的输入文件。这里选用2个文件名分别为file01和file02的文件进行测试。文件内容同需求示例。

  

  4. 将输入文件传输入Hdfs

  在终端输入以下命令即可将整个目录传输进Hdfs(input目录下的所有文件将会被送进Hdfs下名为input01的目录里),请根据MapReduce工程包实际路径对如下命令略作修改即可:

 ./bin/hadoop fs -put ../workspace/Hadoop_t1/input/ input01

  5. 在工程包中新建一个WordCount类并将上面的源代码拷贝进去。

  6. 调整项目运行参数:右键项目 -> “Run As" -> ”Run Configurations"

  

  需要添加的就是"Program arguments"下的那些代码。它们其实是作为命令行参数传递进程序的,第一段是输入文件路径;第二段是输出文件路径。

  路径的格式为 "[主机IP地址:hdfs端口] + [输入/输出目录在hdfs中的路径]"。

  可以输入以下命令查看输入目录路径:

 ./bin/hadoop fs -ls

  

  7. 点击"Run"运行程序。

  8. 执行以下命令查看结果:

 ./bin/hadoop fs -cat output01/*

  

  这些主机和Hdfs的文件传递,显示也可以使用Eclipse,更方便容易。在此就不提了。

  

小结

  1. 多多熟练Hadoop平台下MapReduce项目基本创建流程。

  2. WordCount是一个很经典的Hadoop示例,它虽然简单,但具有很大的代表性。

  3. 从某个程度上来说也反映了其设计的初衷,对日志文件的分析。

Eclipse上运行第一个Hadoop实例 - WordCount(单词统计程序)的更多相关文章

  1. 第六篇:Eclipse上运行第一个Hadoop实例 - WordCount(单词统计程序)

    需求 计算出文件中每个单词的频数.要求输出结果按照单词的字母顺序进行排序.每个单词和其频数占一行,单词和频数之间有间隔. 比如,输入两个文件,其一内容如下: hello world hello had ...

  2. hadoop学习---运行第一个hadoop实例

    hadoop环境搭建好后,运行第wordcount示例 1.首先启动hadoop:sbin/start-dfs.sh,sbin/start-yarn.sh(必须能够正常运行)   2.进入到hadoo ...

  3. 第二章 mac上运行第一个appium实例

    一.打开appium客户端工具 1      检查环境是否正常运行: 点击左边第三个图标 这是测试你环境是否都配置成功了 2      执行的过程中,遇到Could not detect Mac OS ...

  4. 在Hadoop1.2.1上运行第一个Hadoop程序FileSystemCat

  5. 运行第一个Hadoop程序,WordCount

    系统: Ubuntu14.04 Hadoop版本: 2.7.2 参照http://www.cnblogs.com/taichu/p/5264185.html中的分享,来学习运行第一个hadoop程序. ...

  6. 在Eclipse上运行Spark(Standalone,Yarn-Client)

    欢迎转载,且请注明出处,在文章页面明显位置给出原文连接. 原文链接:http://www.cnblogs.com/zdfjf/p/5175566.html 我们知道有eclipse的Hadoop插件, ...

  7. 在Hadoop上运行基于RMM中文分词算法的MapReduce程序

    原文:http://xiaoxia.org/2011/12/18/map-reduce-program-of-rmm-word-count-on-hadoop/ 在Hadoop上运行基于RMM中文分词 ...

  8. linux下在eclipse上运行hadoop自带例子wordcount

    启动eclipse:打开windows->open perspective->other->map/reduce 可以看到map/reduce开发视图.设置Hadoop locati ...

  9. 【hadoop】在eclipse上运行WordCount的操作过程

    序:本以为今天花点时间将WordCount例子完全理解到,但高估自己了,更别说我只是在大学选修一学期的java,之后再也没碰过java语言了 总的来说,从宏观上能理解具体的程序思路,但具体到每个代码有 ...

随机推荐

  1. SVN错误及处理

    SVN无法读取current修复方法 Can't read file : End of file found 文件:repository/db/txn_current.repository/db/cu ...

  2. Key Figure、Exception Aggreagion、Non-Cumulative KeyFigure

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  3. 使用celery之深入celery配置(转)

    原文:http://www.dongwm.com/archives/shi-yong-celeryzhi-shen-ru-celerypei-zhi/ 前言 celery的官方文档其实相对还是写的很不 ...

  4. spring主要的作用?

    在SSH框假中spring充当了管理容器的角色.我们都知道Hibernate用来做持久层,因为它将JDBC做了一个良好的封装,程序员在与数据库进行交互时可以不用书写大量的SQL语句.Struts是用来 ...

  5. caffe中各层的作用:

    关于caffe中的solver: cafffe中的sover的方法都有: Stochastic Gradient Descent (type: "SGD"), AdaDelta ( ...

  6. GeoHash

    查找是我们经常会碰到的问题,以前我做过一个这样的算法,在有序的数列(80万条左右),这批数据是根据维度由小到大排序的,寻找已知数据的位置,并且所相应的运算,由于这个算法要在嵌入式系统中做,如果一次在内 ...

  7. Oracle新增客户端网络配置使用scott出现错误

    错误一   测试提示用户密码过期 解决方法:使用sys用户登录数据库 sqlplus sys/密码  as sysdba; 修改scott用户密码 alter user scott identifie ...

  8. 【linux】linux下yum安装后Apache、php、mysql默认安装路径

    原文:http://blog.csdn.NET/u010175124/article/details/27322757apache:如果采用RPM包安装,安装路径应在 /etc/httpd目录下apa ...

  9. Educational Codeforces Round 14 E.Xor-sequences

    题目链接 分析:K很大,以我现有的极弱的知识储备,大概应该是快速幂了...怎么考虑这个快速幂呢,用到了dp的思想.定义表示从到的合法路径数.那么递推式就是.每次进行这样一次计算,那么序列的长度就会增加 ...

  10. [双连通分量] POJ 3177 Redundant Paths

    Redundant Paths Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 13712   Accepted: 5821 ...