`
ruilinruirui
  • 浏览: 1042660 次
文章分类
社区版块
存档分类
最新评论

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics