首页 > 其他分享 >MapReduce学习之MapJoin案例实现

MapReduce学习之MapJoin案例实现

时间:2024-06-01 16:03:21浏览次数:9  
标签:案例 hadoop new MapReduce MapJoin job org apache import

MapReduce学习之MapJoin案例实现

1.当前main方法所在的入口类

package com.shujia.mr.mapJoin;

import com.shujia.mr.reduceJoin.ReduceJoin;
import com.shujia.mr.reduceJoin.ReduceJoinMapper;
import com.shujia.mr.reduceJoin.ReduceJoinReducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.FileNotFoundException;
import java.io.IOException;

public class MapJoin {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        /*
            TODO:
                需求:需要使用Map端对基本信息数据和成绩数据进行关联
                分析:
                    ① 先读取students.txt文件中的数据
                    ② 通过其他方式再读取score.txt中的数据
                问题:
                    由于需要添加两种文件的数据,同时map函数计算时,是按行读取数据的,上一行和下一行之间没有关系
                        于是思路:
                            ① 先读取score.txt中的数据到一个HashMap中
                            ② 之后再将HashMap中的数据和按行读取的Students.txt中的每一行数据进行匹配
                            ③ 将关联的结果再进行写出操作
                        注意:
                            需要在读取students.txt文件之前就将score.txt数据读取到HashMap中
         */

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "MapJoin");
        job.setJarByClass(MapJoin.class);
        job.setMapperClass(MapJoinMapper.class);


        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        // TODO 4.设置数据的输入和输出路径

        // 本地路径
        FileSystem fileSystem = FileSystem.get(job.getConfiguration());
        Path outPath = new Path("hadoop/out/mapJoin");
        Path studentInpath = new Path("hadoop/data/students.txt");

        // TODO 可以在当前位置将需要在setup函数中获取的路径进行缓存
        job.addCacheFile(new Path("hadoop/out/count/part-r-00000").toUri());


        if (!fileSystem.exists(studentInpath)) {
            throw new FileNotFoundException(studentInpath+"不存在");
        }
        TextInputFormat.addInputPath(job,studentInpath);


        if (fileSystem.exists(outPath)) {
            System.out.println("路径存在,开始删除");
            fileSystem.delete(outPath,true);
        }
        TextOutputFormat.setOutputPath(job,outPath);

        // TODO 5.提交任务开始执行
        job.waitForCompletion(true);

    }
}

2.Map端

package com.shujia.mr.mapJoin;

import jdk.nashorn.internal.runtime.regexp.joni.Config;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;

public class MapJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
    HashMap<String, Integer> scoreHashMap;

    public MapJoinMapper() {
        this.scoreHashMap = new HashMap<>();
    }

    /**
     * 在每个MapTask被执行时,都会先执行一次setup函数,可以用于加载一些数据
     *
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void setup(Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        /*
            TODO 需要读取 score.txt 中的数据
                如果在本地执行,那么可以通过BufferedReader按行读取数据,如果是在HDFS中获取数据
                    需要通过FileSystem创建IO流进行读取,并且FileSystem也可以读取本地文件系统中的数据
         */
        /*
            TODO 问题:
                ① 对于每个MapTask都需要执行一次 setup 函数,那么当MapTask较多时,每个MapTask都保存一个HashMap的Score数据
                        该数据是保存在内存当中的  于是对于MapJoin有一个使用的前提条件
                    一个大表和一个小表进行关联,其中将小表的数据加载到集合中,大表按行进行读取数据
                    同时小表要小到能保存在内存中,没有内存压力 通常是在 25M-40M以内的数据量
         */

        Configuration configuration = context.getConfiguration();
        FileSystem fileSystem = FileSystem.get(configuration);
        // new Path(filePath).getFileSystem(context.getConfiguration());
        // 通过context中的getCacheFiles获取缓存文件路径
        URI[] files = context.getCacheFiles();
        for (URI filePath : files) {
            FSDataInputStream open = fileSystem.open(new Path(filePath));
//            FSDataInputStream open = fileSystem.open(new Path("hadoop/out/count/part-r-00000"));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open));
            String oneScore = null;
            while ((oneScore = bufferedReader.readLine()) != null) {
                String[] column = oneScore.split("\t");
                scoreHashMap.put(column[0], Integer.valueOf(column[1]));
            }

        }
        System.out.println("Score数据加载完成,已存储到HashMap中");
        Configuration configuration1 = context.getConfiguration();
        FileSystem fileSystem1 = FileSystem.get(configuration1);
        URI[] files1 = context.getCacheFiles();
        for(URI fillPath : files1){
            FSDataInputStream open1 = fileSystem1.open(new Path(fillPath));
            BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(open1));
            String oneScore1 = null;
            while((oneScore1 = bufferedReader1.readLine()) != null){
                String[] column1 = oneScore1.split("\t");
                scoreHashMap.put(column1[0], Integer.valueOf(column1[1]));
            }

        }


    }

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        // 1500100004,葛德曜,24,男,理科三班
        String oneStuInfo = value.toString();

        String[] columns = oneStuInfo.split(",");
        if (columns.length == 5) {
            String id = columns[0];
            // TODO 通过HashMap获取数据,如果没有获取到,那么阁下如何应对?
            Integer score = scoreHashMap.get(id);
            oneStuInfo += (","+score);
            context.write(new Text(oneStuInfo), NullWritable.get());
        }

    }
}

标签:案例,hadoop,new,MapReduce,MapJoin,job,org,apache,import
From: https://blog.csdn.net/m0_58050808/article/details/139335208

相关文章

  • [转帖]一次Java内存占用高的排查案例,解释了我对内存问题的所有疑问
     https://segmentfault.com/a/1190000044152595 原创:扣钉日记(微信公众号ID:codelogs),欢迎分享,非公众号转载保留此声明。问题现象7月25号,我们一服务的内存占用较高,约13G,容器总内存16G,占用约85%,触发了内存报警(阈值85%),而我们是按容器内存60%(9.6G)的比例配置的JVM堆内存......
  • 204页 | MES项目需求案例方案:效率+精细化+品质+数据互联(免费下载)
     【1】关注本公众号,转发当前文章到微信朋友圈【2】私信发送MES项目需求案例方案【3】获取本方案PDF下载链接,直接下载即可。如需下载本方案PPT/WORD原格式,请加入微信扫描以下方案驿站知识星球,获取上万份PPT/WORD解决方案!!!感谢支持!!!......
  • XML Web 服务技术解析:WSDL 与 SOAP 原理、应用案例一览
    XMLWeb服务是一种用于在网络上发布、发现和使用应用程序组件的技术。它基于一系列标准和协议,如WSDL、SOAP、RDF和RSS。下面是一些相关的内容:WSDL(Web服务描述语言):用于描述Web服务的基于XML的语言,定义了服务的接口、操作和消息格式SOAP(简单对象访问协议):是一种基于XML的协议......
  • SpringBoot案例,通关版
    项目目录此项目为了伙伴们可以快速入手SpringBoot项目,全网最详细的版本,每个伙伴都可以学会,这个项目每一步都会带大家做,学完后可以保证熟悉SpringBoot的开发流程项目介绍:项目使用springboot+mybatis进行开发带你一起写小项目先把初始环境给你们第一步新建springboot项......
  • kaggle竞赛系列基于图像对水稻分类代码案例
    目录依赖环境代码导入依赖包定义数据集路径:创建训练集、验证集和测试集的文件夹:代码的作用:设置新的数据集路径与类别名称代码的作用:定义数据预处理和增强变换:代码的作用:定义数据集评估划分与batch大小代码的作用:可视化代码的作用: 评估可视化代码的作用:网络结......
  • mapreduce的多种格式文件输出-自定义OutputFormat
    /***@description:mapreduce多种格式的文件输出方式*/publicclassMultipleTypeOutputFormat<K,V>extendsFileOutputFormat<K,V>{privatestaticfinalStringORCEXTENSION=".orc";privatestaticfinalStringCSVEXTENSION=".c......
  • 用python写一个抖店选品的案例
    今天我使用Python编写抖店选品策略的简单案例。我们将使用pandas库处理数据,并假设你已经安装了pandas库。首先,我们需要准备以下数据:1.销售数据:包含商品、销售日期、销售额等信息。2.用户评价数据:包含商品、评价日期、评价分数等信息。3.库存数据:包含商品、库存信息。4.......
  • python 使用面向对象思想解决案例
    要求:步骤一文件读取:父类子类1子类2测试效果图步骤二数据计算:步骤三可视化开发效果图知识点:魔术方法之字符串方法__str__,构造方法__init__pass关键字,占位语句,用来保证函数或类定义的完整性,表示无内容抽象类:含有抽象方法的类抽象方法:没有具体实现......
  • JAVA【案例4-8】模拟物流快递系统程序设计
    【模拟物流快递系统程序设计】1、案例描述网购已成为人们生活的重要组成部门,当人们在购物网站中下订单后,订单中的货物就会在经过一系列的流程后,送到客户的手中。而在送货期间,物流管理人员可以在系统中查看所有物品的物流信息。编写一个模拟物流快递系统的程序,模拟后台系统处......
  • C#中接口的显式实现与隐式实现及其相关应用案例
    C#中接口的显式实现与隐式实现最近在学习演化一款游戏项目框架时候,框架作者巧妙使用接口中方法的显式实现来变相对接口中方法进行“密封”,增加实现接口的类访问方法的“成本”。接口的显式实现和隐式实现:先定义一个接口,接口中有这两个方法。publicinterfaceICanSingSong{......