MapReduce原理
以WordCount程序为例,假设有三台DataNode,每台DataNode有不一样的数据,如下表格所示:
DataNode1
|
DataNode2
|
DataNode3
|
who are you are
|
who am i are
|
who is he am
|
经过Map函数后,生成以下键值对:
DataNode1
|
DataNode2
|
DataNode3
|
who 1
are 1
you 1
are 1
|
who 1
am 1
i 1
are 1
|
who 1
is 1
he 1
am 1
|
然后按照key值排序,变成以下键值对:
DataNode1
|
DataNode2
|
DataNode3
|
are 1
are 1
who 1
you 1
|
am 1
are 1
i 1
who 1
|
am 1
he 1
is 1
who 1
|
如果有Combiner函数的话,则把相同的key进行计算,我们可以吧Combiner函数当做一个miniReduce函数:
DataNode1
|
DataNode2
|
DataNode3
|
are 2
who 1
you 1
|
am 1
are 1
i 1
who 1
|
am 1
he 1
is 1
who 1
|
如果有Partition函数的话,则进行分区,分几个区就有几个Reducer同时进行运算,然后就会生成几个不一样的结果文件;默认只有一个Reducer进行工作。
这里先讲一个Reducer的情况,数据先从三个DataNode中Copy过来,然后Merge到Reducer中去:
Reducer
|
are 2
who 1
you 1
am 1
are 1
i 1
who 1
am 1
he 1
is 1
who 1
|
然后对数据按照key进行排序(Sort),Copy,Merge,Sort过程统称为Shuffle过程:
Reducer
|
am 1
am 1
are 2
are 1
he 1
i 1
is 1
you 1
who 1
who 1
who 1
|
然后数据经过Reduce函数后,生成以下输出文件:
Reducer
|
am 2
are 3
he 1
i 1
is 1
you 1
who 3
|
到这里为止,整个MapReduce过程也就完成了。
如果有多个Reducer的话,不同的是数据会分开Copy到不同的机器中,也就是分开计算,然后Copy到每个Reducer中的数据都会经过Merge,Sort,Reduce过程,最后每个Reducer都会生成一个结果文件。