Hadoop Streaming 实战: c++编写map&reduce程序

1. 输入文件:
姓名 年龄(以'/t’分割)
eg:
张三 15
李四 15
张三 16
张三 15

输出:将姓名和年龄相同的归一,并输出其人数
eg:上述输入,输出为:

姓名 年龄 人数(以'/t’分割)
张三 15 2
李四 15 1
张三 16 1

2. map程序:

#include 
#include 
 
  
using namespace std;
 
  
int main(int argc, char** argv)
{
    string name,age;
 
  
    //读入姓名、年龄
    while(cin >> name >> age)
    {
        //输出姓名、年龄、人数
        cout << name << "/t" << age  << "/t" << "1" << endl;
    }
    return 0;
}

编译生成可执行程序:
g++ -o mapper mapper.cpp

3. reducer程序:

#include 
#include 
#include 
 
  
using namespace std;
 
  
int main(int argc, char** argv)
{
    string key, value;
    int num;
    
    //个数统计
    mapint> count_stat;
    mapint>::iterator it_count_stat;
    
    //读入数据并插入map
    while(cin >> key >> value >> num)
    {
        string tmp_key = key + "/t" + value;
    
        //插入数据
        it_count_stat = count_stat.find(tmp_key);
        if(it_count_stat != count_stat.end())
        {
            (it_count_stat->second)++;
        }
        else
        {
            count_stat.insert(make_pair(tmp_key, 1));
        }
    }
 
  
    //输出统计结果
    for(it_count_stat = count_stat.begin(); it_count_stat != count_stat.end(); it_count_stat++)
    {
        cout<first<<"/t"<second<


      
    }
 
  
    return 0;
}


编译生成可执行程序:
g++ -o reducer reducer.cpp

4. 测试数据:

张三    15
李四    20
张三    15
张三    16

5. 单机测试运行:

$ cat test.txt | ./mapper  | ./reducer 
    李四    20    1
    张三    15    2
    张三    16    1

6. Hadoop集群运行:
以'/t’作为分隔符,并以前两个字段作为key,reduce任务3个,输入命令:

$ hadoop fs -put test.txt /user/test.txt
$ hadoop streaming -D stream.map.output.field.separator='/t' /
    -D stream.num.map.output.key.fields=2 /
    -input /user/test.txt /
    -output /user/tmp_1324 /
    -mapper ./mapper -reducer ./reducer /
    -file mapper -file reducer /
    -jobconf mapred.reduce.tasks=3 /
    -jobconf mapre.job.name="c++_test" 

7.查看输出:

$ hadoop fs -cat /user/tmp_1324/part-00000
李四    20      1
张三    16      1
$ hadoop fs -cat /user/part-00001
$ hadoop fs -cat /user/part-00002
张三    15      2

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值