測试hadoop版本号:2.4 

Map端聚合的应用场景:当我们仅仅关心全部数据中的部分数据时,而且数据能够放入内存中。

使用的优点:能够大大减小网络数据的传输量,提高效率;

一般编程思路:在Mapper的map函数中读入全部数据,然后加入到一个List(队列)中。然后在cleanup函数中对list进行处理。输出我们关系的少量数据。

实例:

在map函数中使用空格分隔每行数据。然后把每一个单词加入到一个堆栈中,在cleanup函数中输出堆栈中单词次数比較多的单词以及次数。

  1. package fz.inmap.aggregation;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.PriorityQueue;
  5. import org.apache.hadoop.conf.Configuration;
  6. import org.apache.hadoop.conf.Configured;
  7. import org.apache.hadoop.fs.Path;
  8. import org.apache.hadoop.io.IntWritable;
  9. import org.apache.hadoop.io.LongWritable;
  10. import org.apache.hadoop.io.Text;
  11. import org.apache.hadoop.mapreduce.Job;
  12. import org.apache.hadoop.mapreduce.Mapper;
  13. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
  14. import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
  15. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
  16. import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
  17. import org.apache.hadoop.util.Tool;
  18. import org.apache.hadoop.util.ToolRunner;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. public class InMapArrgegationDriver extends Configured implements Tool{
  22. public static Logger log = LoggerFactory.getLogger(InMapArrgegationDriver.class);
  23. /**
  24. * @throws Exception
  25. *
  26. */
  27. public static void main(String[] args) throws Exception {
  28. ToolRunner.run(new Configuration(), new InMapArrgegationDriver(),args);
  29. }
  30. @Override
  31. public int run(String[] arg0) throws Exception {
  32. if(arg0.length!=3){
  33. System.err.println("Usage:\nfz.inmap.aggregation.InMapArrgegationDriver <in> <out> <maxNum>");
  34. return -1;
  35. }
  36. Configuration conf = getConf();
  37. // System.out.println(conf.get("fs.defaultFS"));
  38. Path in = new Path(arg0[0]);
  39. Path out= new Path(arg0[1]);
  40. out.getFileSystem(conf).delete(out, true);
  41. conf.set("maxResult", arg0[2]);
  42. Job job = Job.getInstance(conf,"in map arrgegation job");
  43. job.setJarByClass(getClass());
  44. job.setInputFormatClass(TextInputFormat.class);
  45. job.setOutputFormatClass(TextOutputFormat.class);
  46. job.setMapperClass(InMapMapper.class);
  47. job.setMapOutputKeyClass(Text.class);
  48. job.setMapOutputValueClass(IntWritable.class);
  49. // job.setOutputKeyClass(LongWritable.class);
  50. // job.setOutputValueClass(VectorWritable.class);
  51. job.setNumReduceTasks(0);
  52. // System.out.println(job.getConfiguration().get("mapreduce.job.reduces"));
  53. // System.out.println(conf.get("mapreduce.job.reduces"));
  54. FileInputFormat.setInputPaths(job, in);
  55. FileOutputFormat.setOutputPath(job, out);
  56. return job.waitForCompletion(true)?0:-1;
  57. }
  58. protected static class InMapMapper extends Mapper<LongWritable,Text,Text,IntWritable>{
  59. private ArrayList<Word> words = new ArrayList<Word>();
  60. private PriorityQueue<Word> queue;
  61. private int maxResult;
  62. protected void setup(Context cxt){
  63. maxResult = cxt.getConfiguration().getInt("maxResult", 10);
  64. }
  65. protected void map(LongWritable key, Text value,Context cxt){
  66. String [] line = value.toString().split(" "); // use blank to split
  67. for(String word:line){
  68. Word curr = new Word(word,1);
  69. if(words.contains(curr)){
  70. // increase the exists word's frequency
  71. for(Word w:words){
  72. if(w.equals(curr)){
  73. w.frequency++;
  74. break;
  75. }
  76. }
  77. }else{
  78. words.add(curr);
  79. }
  80. }
  81. }
  82. protected void cleanup(Context cxt) throws InterruptedException,IOException{
  83. Text outputKey = new Text();
  84. IntWritable outputValue = new IntWritable();
  85. queue = new PriorityQueue<Word>(words.size());
  86. queue.addAll(words);
  87. for(int i=0;i< maxResult;i++){
  88. Word tail = queue.poll();
  89. if(tail!=null){
  90. outputKey.set(tail.value);
  91. outputValue.set(tail.frequency);
  92. log.info("key is {},value is {}", outputKey,outputValue);
  93. cxt.write(outputKey, outputValue);
  94. }
  95. }
  96. }
  97. }
  98. }

使用到的Word类

  1. package fz.inmap.aggregation;
  2. public class Word implements Comparable<Word>{
  3. public String value;
  4. public int frequency;
  5. public Word(String value,int frequency){
  6. this.value=value;
  7. this.frequency=frequency;
  8. }
  9. @Override
  10. public int compareTo(Word o) {
  11. return o.frequency-this.frequency;
  12. }
  13. @Override
  14. public boolean equals(Object obj){
  15. if(obj instanceof Word){
  16. return value.equalsIgnoreCase(((Word)obj).value);
  17. }else{
  18. return false;
  19. }
  20. }
  21. }

查看输出结果,能够看日志(因为在程序中输出了日志,所以在日志中也能够查看到);

或者查看输出结果:

总结:使用map端聚合,尽管能够大大减小网络传输数据量。提高效率,可是我们在应用的时候还是须要考虑实际的应用环境。比方。假设使用上面的算法来计算最大单词频率的前10个,然后还是使用上面的代码。就会有问题。

每一个mapper会处理并输出自己的单词词频最大的10个单词,并没有考虑到全部数据。这样在reducer端整合的时候就会可能会忽略部分数据,造成终于结果的错误。

分享,成长,快乐

转载请注明blog地址:http://blog.csdn.net/fansy1990

hadoop编程小技巧(1)---map端聚合的更多相关文章

  1. hadoop编程小技巧(5)---自定义输入文件格式类InputFormat

    Hadoop代码测试环境:Hadoop2.4 应用:在对数据需要进行一定条件的过滤和简单处理的时候可以使用自定义输入文件格式类. Hadoop内置的输入文件格式类有: 1)FileInputForma ...

  2. hadoop编程小技巧(5)---自己定义输入文件格式类InputFormat

    Hadoop代码測试环境:Hadoop2.4 应用:在对数据须要进行一定条件的过滤和简单处理的时候能够使用自己定义输入文件格式类. Hadoop内置的输入文件格式类有: 1)FileInputForm ...

  3. hadoop编程小技巧(7)---自己定义输出文件格式以及输出到不同文件夹

    代码測试环境:Hadoop2.4 应用场景:当须要定制输出数据格式时能够採用此技巧,包含定制输出数据的展现形式.输出路径.输出文件名称称等. Hadoop内置的输出文件格式有: 1)FileOutpu ...

  4. Java编程小技巧(1)——方法传回两个对象

    原文地址:Java编程小技巧(1)--方法传回两个对象 | Stars-One的杂货小窝 题目是个伪命题,由Java语法我们都知道,方法要么返回一个对象,要么就不返回 当有这样的情况,我们需要返回两个 ...

  5. Shellcode编程小技巧

    工作需要,需要注入其他程序监控一些东西,检测到的数据通过WM_COPY 消息发送给显示窗体.(大体是这样的还没定稿) ##1 选择一个框架 ## tombkeeper/Shellcode_Templa ...

  6. 学会这些 pycharm 编程小技巧,编程效率提升 10 倍

    PyCharm 是一款非常强大的编写 python 代码的工具.掌握一些小技巧能成倍的提升写代码的效率,本篇介绍几个经常使用的小技巧. 一.分屏展示 当你想同时看到多个文件的时候: 1.右击标签页: ...

  7. android 编程小技巧(持续中)

    first:     Intent跳转一般存用于Activity类,可是若要在非activity类里跳转的话,解决方法是在startActivity(intent)前加mContext即上下文,终于为 ...

  8. 编程小技巧之 Linux 文本处理命令

    合格的程序员都善于使用工具,正所谓君子性非异也,善假于物也.合理的利用 Linux 的命令行工具,可以提高我们的工作效率. 本文简单的介绍三个能使用 Linux 文本处理命令的场景,给大家开阔一下思路 ...

  9. WTL编程小技巧汇编

    1.设置窗体生成大小并中央显示窗口 2.设置窗体最大/小尺寸 3.动态设置窗体标题 4.设置对话框的字体和背景颜色 5.设置窗体控件默认字体 以下技巧可应用于SDI和MDI程序: 1.设置窗体生成大小 ...

随机推荐

  1. Spring 自动代理

    在传统的基于代理类的AOP实现中,每个代理都是通过ProxyFactoryBean织入切面代理,在实际开发中,非常多的Bean每个都配置ProxyFactoryBean开发维护量巨大.解决方案:自动创 ...

  2. 命令——tree

    tree——以树形结构显示目录文件 [root@centos71 ~]# yum provides tree Loaded plugins: fastestmirror Loading mirror ...

  3. react native之使用AsyncStorage 进行数据持久化存储

    新建AsncStorageDemoPage.js import React, {Component} from 'react'; import { StyleSheet, View, Text, Bu ...

  4. Linux内核设计与实现 总结笔记(第十三章)虚拟文件系统

    一.通用文件系统接口 Linux通过虚拟文件系统,使得用户可以直接使用open().read().write()访问文件系统,这种协作性和泛型存取成为可能. 不管文件系统是什么,也不管文件系统位于何种 ...

  5. Java——网络

    [通信协议分层]   (1)为什么要分层?  

  6. Mobile的HTML5网页内快速滚动和回弹的效果

    style="overflow: auto;-webkit-overflow-scrolling: touch; 这个可以让页面在Native端滚动时模拟原生的弹性滚动效果 下面是微信浏览器 ...

  7. IBM Security App Scan Standard 工具的使用

    1.AppScan是什么? AppScan是IBM的一款web安全扫描工具,可以利用爬虫技术进行网站安全渗透测试,根据网站入口自动对网页链接进行安全扫描,扫描之后会提供扫描报告和修复建议等. AppS ...

  8. JS备忘--子父页面获取元素属性、显示时间,iframe之间互相调用函数

    //页面加载完成后执行 $(function () { getHW();}); //当用户改变浏览器大小改变时触发 $(window).resize(function () { setHW(); }) ...

  9. 阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第2节 线程实现方式_1_并发与并行

    并发,相当于 一个人吃两个馒头,吃一口这个再吃一口另外一个.这里是cpu一会执行任务1,一会又执行任务2 并行,相当于两个人 吃两个馒头,各自吃各自的,这样速度就会快

  10. Windows Server 2008 R2 为用户“IIS APPPOOL\DefaultAppPool”授予的权限不足,无法执行此操作

    报表开发与部署好后,也嵌入到aspx页面中了,使用VS自带的Web服务器组件,一切正常,当部署到IIS中的时,出现了如下错误: 为用户“IIS APPPOOL\DefaultAppPool”授予的权限 ...