MapReducer基础案例整理

本文介绍了使用MapReduce实现数据去重、排序加序号及计算平均成绩三个案例的具体实现过程,包括Mapper、Reducer的设计与测试类的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、数据去重--Mapper类:

public class DataMapper extends Mapper<LongWritable,Text,Text,Text> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        String[] split = value.toString().split(" ");
        context.write(new Text(split[0]),new Text(split[1]+" "+split[2]));

    }
}
复制代码

二、Reducer类:

public class DataReducer extends Reducer<Text,Text,Text,Text> {
    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {

        StringBuffer d = new StringBuffer();

        for (Text value : values) {
            d.append(value);
        }
        context.write(key,new Text(d.toString()));

    }
}
复制代码

三、测试类:

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJarByClass(Main.class);

        job.setMapperClass(DataMapper.class);
        job.setReducerClass(DataReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        File file = new File("E:\\fengzeze\\输出");
        if (file.exists()) {
            FileUtils.deleteDirectory(file);
        }
        FileInputFormat.setInputPaths(job, new Path("E:\\fengzeze\\数据"));
        FileOutputFormat.setOutputPath(job, new Path("E:\\fengzeze\\输出"));
        job.setNumReduceTasks(1);
        boolean b = job.waitForCompletion(true);
        System.exit(b ? 0 : 1);
    }
}
复制代码

设计思路:

[数据去重]的最终目标是让[原始数据]中[出现次数][超过一次]的数据在输出文件中只出现一次。我们自然而然会想到将同一个数据的所有记录都交给一台reduce机器,无论这个数据出现多少次,只要在最终结果中输出一次就可以了。具体就是[reduce的输入]应该以数据作为key,而对value-list则没有要求。当reduce接收到一个<key,value-list>时就直接将key复制到输出的key中,并将value设置成空值。

==========================================================================

一、数据排序加序号--Mapper类:

public class DataSorting extends Mapper<LongWritable,Text,Text,NullWritable> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        context.write(new Text(value.toString()),NullWritable.get());
    }
}
复制代码

二、Reducer类:

用for循环递增1,在Key位置上输出i+1。

public class DataReducer extends Reducer<Text,NullWritable,Text,Text> {
    List<Integer> lien = new ArrayList<>();

    @Override
    protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
        lien.add(Integer.parseInt(key.toString()));
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        Collections.sort(lien);
        for (int i = 0; i < lien.size(); i++) {
            context.write(new Text(String.valueOf(i+1)), new Text(String.valueOf(lien.get(i))));
        }
    }
}
复制代码

三、测试类:

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);

        job.setJarByClass(Test.class);

        job.setMapperClass(DataSorting.class);
        job.setReducerClass(DataReducer.class);

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

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

        File file = new File("E:\\fengzeze\\数据排序\\输出");
        if (file.exists()){
            FileUtils.deleteDirectory(file);
        }
        FileInputFormat.setInputPaths(job,new Path("E:\\fengzeze\\数据排序\\数据"));
        FileOutputFormat.setOutputPath(job,new Path("E:\\fengzeze\\数据排序\\输出"));

        job.setNumReduceTasks(1);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
复制代码

设计思路:

但是在使用之前首先需要了解它的默认排序规则。它是按照key值进行排序的,如果key为封装int的IntWritable类型,那么MapReduce按照数字大小对key排序,如果key为封装为String的Text类型,那么MapReduce按照字典顺序对字符串排序。没有用Combiner。

==========================================================================

一、平均成绩--Mapper类:

public class AMapper extends Mapper<LongWritable,Text,Text,IntWritable> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        String[] split = value.toString().split(" ");

        context.write(new Text(split[0]),new IntWritable(Integer.parseInt(split[1])));
    }
}
复制代码

二、Reducer类:

public class AReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int courseCount = 0;
        //定义科目的数量
        int sum = 0;
        //定义总成绩
        int average = 0;
        //定义平均值

        for (IntWritable value : values) {
            sum += value.get();
            courseCount ++;
        }

        average = sum / courseCount;
        context.write(new Text(key),new IntWritable(average));
    }
}
复制代码

测试类:

public class AvTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);

        job.setJarByClass(AvTest.class);

        job.setMapperClass(AMapper.class);
        job.setReducerClass(AReducer.class);

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

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

        File file = new File("E:\\fengzeze\\平均成绩\\输出");
        if (file.exists()){
            FileUtils.deleteDirectory(file);
        }
        FileInputFormat.setInputPaths(job,new Path("E:\\fengzeze\\平均成绩\\数据"));
        FileOutputFormat.setOutputPath(job,new Path("E:\\fengzeze\\平均成绩\\输出"));

        job.setNumReduceTasks(1);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
复制代码

设计思路:

1.Map的结果会通过partion分发到Reducer,Reducer做完Reduce操作后,将通过以格式OutputFormat输出。

2.Mapper最终处理的结果对<key,value>,会送到Reducer中进行合并,合并的时候,有相同key的键/值对则送到同一个 Reducer上。Reducer是所有用户定制Reducer类地基础,它的输入是key和这个key对应的所有value的一个迭代器,同时还有 Reducer的上下文。Reduce的结果由Reducer.Context的write方法输出到文件中。

### C++ 中的 MapReduce 实现 #### 什么是 MapReduce? MapReduce 是一种用于处理大规模数据集的编程模型,最初由 Google 提出[^3]。它通过两个主要阶段来简化分布式计算中的复杂性:**Map** 和 **Reduce**。 - **Map** 阶段负责将输入数据转换为键值对的形式。 - **Reduce** 阶段则聚合这些键值对,生成最终结果。 在 C++ 中实现 MapReduce 可以利用 STL 容器(如 `std::map` 或 `std::unordered_map`),以及自定义的数据流管理工具。 --- #### C++ 中的 MapReduce 库 目前存在一些开源库可以用来实现在 C++ 中的 MapReduce 功能: 1. **Boost.MPI** Boost.MPI 是一个基于 MPI (Message Passing Interface) 的库,支持消息传递接口标准。虽然其本身并不是专门为 MapReduce 设计的,但它可以通过扩展实现类似的并行计算模式[^4]。 2. **cpp-mapreduce** 这是一个轻量级的 C++ MapReduce 实现框架,专注于提供易用性和灵活性。它可以读取文件目录并将每个文件名及其对应的输入流作为键值对分配给不同的 Map 任务[^1]。 3. **Hadoop Pipes** Hadoop 支持通过 Pipes 接口调用外部程序语言编写的 Mapper 和 Reducer 函数,其中包括 C++ 编程的支持。这使得开发者能够充分利用 Hadoop 生态系统的强大功能,同时保持使用熟悉的开发环境[^4]。 --- #### 使用 STL 容器模拟 MapReduce 如果不想依赖第三方库,在纯 C++ 环境下也可以手动构建简单的 MapReduce 流程。以下是具体方法: ##### 数据结构的选择 当涉及到存储和操作大量的键值对时,通常会考虑两种容器类型: - 如果只需要唯一性的键集合而不需要关联任何额外的信息,则可以选择 `std::set` 或者 `std::unordered_set`. - 当需要保存每把钥匙对应的具体数值或者对象实例时,则应该选用 `std::map` 或者 `std::unordered_map`. 注意尽管两者都提供了查找、插入等功能,但它们内部实现方式不同——前者基于平衡二叉树,后者则是哈希表;因此性能特征也会有所差异[^2]. 下面给出一段伪代码展示如何运用上述概念完成基本的任务分解过程: ```cpp #include <iostream> #include <vector> #include <string> #include <unordered_map> // Define your custom mapper function here. void myMapper(const std::string& inputLine, std::vector<std::pair<std::string, int>>& outputPairs){ // Split line into words and emit them as pairs of word -> count=1 } int main(){ std::unordered_map<std::string, int> results; // Assume we have some inputs... std::vector<std::string> lines = {"hello world", "this is test"}; std::vector<std::pair<std::string,int>> intermediateResults; for(auto &line : lines){ myMapper(line,intermediateResults); } // Now perform reduction step by aggregating counts per unique key for(auto &[key,value]:intermediateResults){ results[key]+=value; } // Output final result set after reducing all keys together appropriately. for(auto const&[k,v]:results){ std::cout<< k << ":"<< v<<"\n"; } return EXIT_SUCCESS;} ``` 此示例展示了怎样创建自己的映射函数,并将其应用于一系列字符串上,最后再汇总所得的结果形成完整的字典统计信息。 --- ### 总结 无论是采用现有的成熟解决方案还是自己动手搭建简易版本,都可以有效地达成目标即高效地分析海量资料的目的。选择合适的工具取决于项目的特定需求和技术栈偏好等因素考量之后决定最为恰当的做法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值