当前位置: 首页 > news >正文

MapReduce编程实例

需求

输入文件:文本文件
每行格式:

  • <source> <destination> <time>
  • 3个部分由空格隔开
  • 其中source和destination为两个字符串,内部没有空格
  • time为一个浮点数,代表时间(秒为单位)
  • 涵义:可以表示一次电话通话,或表示一次网站访问等

输入可能有噪音:
如果一行不符合上述格式,应该被丢弃,程序需要正确执行
MapReduce计算:统计每对source‐destination的信息
输出

  • <source> <destination> <count> <average time>
  • 每一个source‐destination组合输出一行(注意:顺序相反按不同处理)
  • 每行输出通话次数和通话平均时间(保留3位小数,例如2.300)

编程实现

import java.io.IOException;
import java.util.StringTokenizer;
import java.math.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
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.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class Hw2Part1{

  public static class TokenizerMapper 
       extends Mapper<Object, Text, Text, DoubleWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {

      String line= value.toString();//all text
      String[] lines=line.split("\n");//split to line


      for(String eachline:lines){
         String[] words=eachline.split("\\s+");
         double time=Double.parseDouble(words[2]);
         if(words.length==3&&time>=0){
           context.write(new Text(words[0]+"\t"+words[1]+"\t"),new DoubleWritable(time)); 
         }
      }
    }
  }

  public static class IntSumCombiner
       extends Reducer<Text,DoubleWritable,Text,DoubleWritable> {
    private DoubleWritable result = new DoubleWritable();

    public void reduce(Text key, Iterable<DoubleWritable> values,
                       Context context
                       ) throws IOException, InterruptedException {
      double sum = 0;
      int count=0;
      for (DoubleWritable val : values) {
        sum += val.get();
        count=count+1;
      }
      Text newkey = new Text(key+"\t"+Integer.toString(count)+"\t");


      sum=Math.round(sum/count*1000)/1000.000;
      result.set(sum);
      context.write(newk, result);
    }
  }


  public static class IntSumReducer
       extends Reducer<Text,DoubleWritable,Text,DoubleWritable> {

    private Text result_key= new Text();
    private Text result_value= new Text();
    private byte[] prefix;
    private byte[] suffix;

    protected void setup(Context context) {
      try {
        prefix= Text.encode("count of ").array();
        suffix= Text.encode(" =").array();
      } catch (Exception e) {
        prefix = suffix = new byte[0];
      }
    }

    public void reduce(Text key, Iterable<DoubleWritable> values, 
                       Context context
                       ) throws IOException, InterruptedException {
      double sum = 0;

      for (DoubleWritable val : values) {
        sum += val.get();
      }

      // generate result key
      result_key.set(prefix);
      result_key.append(key.getBytes(), 0, key.getLength());
      result_key.append(suffix, 0, suffix.length);
      context.write(key,new DoubleWritable(sum));
    }
  }

  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> [<in>...] <out>");
      System.exit(2);
    }

    Job job = Job.getInstance(conf, "Hw2Part1");

    job.setJarByClass(Hw2Part1.class);

    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumCombiner.class);
    job.setReducerClass(IntSumReducer.class);

    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(DoubleWritable.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(DoubleWritable.class);

    // add the input paths as given by command line
    for (int i = 0; i < otherArgs.length - 1; ++i) {
      FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }

    // add the output path as given by the command line
    FileOutputFormat.setOutputPath(job,
      new Path(otherArgs[otherArgs.length - 1]));

    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}

编译命令:

javac Hw2Part1.java

打包命令:

jar cfm Hw2Part1.jar Hw2Part1-manifest.txt Hw2Part1*.class

删除hdfs上的output文件:

hdfs dfs -rm -f -r /hw2/output

运行:

hadoop jar ./Hw2Part1.jar /hw2/example-input.txt /hw2/output

相关文章:

  • iOS开发数据库篇—SQLite简单介绍
  • iOS开发拓展篇—音效的播放
  • 基于COOKIE的点击流数据仓库构建思路(一)
  • Tomcat热部署和虚拟目录配置
  • 被遗忘的Logrotate
  • 压合细节
  • windows下安装python科学计算环境,numpy scipy scikit ,matplotlib等
  • IC卡的传输协议(2)-块传输协议T=1续【转】
  • Elasticsearch 2.3.0 老版本升级指南
  • java web
  • Office online server 部署
  • JRE与JDK简介
  • ConcurrentHashMap
  • Oracle语句异常
  • jmeter 302请求测试
  • css选择器
  • HomeBrew常规使用教程
  • Meteor的表单提交:Form
  • node-sass 安装卡在 node scripts/install.js 解决办法
  • Redux系列x:源码分析
  • Selenium实战教程系列(二)---元素定位
  • Vim Clutch | 面向脚踏板编程……
  • 搭建gitbook 和 访问权限认证
  • 汉诺塔算法
  • 后端_ThinkPHP5
  • 回流、重绘及其优化
  • 理清楚Vue的结构
  • 力扣(LeetCode)357
  • 利用阿里云 OSS 搭建私有 Docker 仓库
  • 前端工程化(Gulp、Webpack)-webpack
  • 数据科学 第 3 章 11 字符串处理
  • 思维导图—你不知道的JavaScript中卷
  • 一个完整Java Web项目背后的密码
  • 硬币翻转问题,区间操作
  • 扩展资源服务器解决oauth2 性能瓶颈
  • 组复制官方翻译九、Group Replication Technical Details
  • ​LeetCode解法汇总1410. HTML 实体解析器
  • #微信小程序:微信小程序常见的配置传值
  • (4)事件处理——(7)简单事件(Simple events)
  • (pytorch进阶之路)CLIP模型 实现图像多模态检索任务
  • (超简单)构建高可用网络应用:使用Nginx进行负载均衡与健康检查
  • (附源码)spring boot基于Java的电影院售票与管理系统毕业设计 011449
  • (附源码)计算机毕业设计高校学生选课系统
  • (免费分享)基于springboot,vue疗养中心管理系统
  • (转)用.Net的File控件上传文件的解决方案
  • (总结)Linux下的暴力密码在线破解工具Hydra详解
  • .form文件_SSM框架文件上传篇
  • .form文件_一篇文章学会文件上传
  • .NET Core6.0 MVC+layui+SqlSugar 简单增删改查
  • .NET 表达式计算:Expression Evaluator
  • .NET 反射 Reflect
  • .NET 中什么样的类是可使用 await 异步等待的?
  • .netcore 如何获取系统中所有session_ASP.NET Core如何解决分布式Session一致性问题
  • .NET实现之(自动更新)
  • .Net下C#针对Excel开发控件汇总(ClosedXML,EPPlus,NPOI)