标签:style blog http color io os 使用 java ar
上面是MapReduce的理论部分,下面说实际的应用,下面以MongoDB MapReduce为例说明。
下面是MongoDB官方的一个例子:
> db.things.insert( { _id : 1, tags : [‘dog‘, ‘cat‘] } );
> db.things.insert( { _id : 2, tags : [‘cat‘] } );
> db.things.insert( { _id : 3, tags : [‘mouse‘, ‘cat‘, ‘dog‘] } );
> db.things.insert( { _id : 4, tags : [] } );
> // map function
> map = function(){
... this.tags.forEach(
... function(z){
... emit( z , { count : 1 } );
... }
... );
...};
> // reduce function
> reduce = function( key , values ){
... var total = 0;
... for ( var i=0; i<values.length; i++ )
... total += values[i].count;
... return { count : total };
...};
db.things.mapReduce(map,reduce,{out:‘tmp‘})
{
"result" : "tmp",
"timeMillis" : 316,
"counts" : {
"input" : 4,
"emit" : 6,
"output" : 3
},
"ok" : 1,
}
> db.tmp.find()
{ "_id" : "cat", "value" : { "count" : 3 } }
{ "_id" : "dog", "value" : { "count" : 2 } }
{ "_id" : "mouse", "value" : { "count" : 1 } }
例子很简单,计算一个标签系统中每个标签出现的次数。
这里面,除了emit函数之外,所有都是标准的js语法,这个emit函数是非常重要的,可以这样理解,当所有需要计算的文档(因为在mapReduce时,可以对文档进行过滤,接下来会讲到)执行完了map函数,map函数会返回key_values对,key即是emit中的第一个参数key,values是对应同一key的emit的n个第二个参数组成的数组。这个key_values会作为参数传递给reduce,分别作为第1.2个参数。
reduce函数的任务就是将key-values变成key-value,也就是把values数组变成一个单一的值value。当key-values中的values数组过大时,会被再切分成很多个小的key-values块,然后分别执行Reduce函数,再将多个块的结果组合成一个新的数组,作为Reduce函数的第二个参数,继续Reducer操作。可以预见,如果我们初始的values非常大,可能还会对第一次分块计算后组成的集合再次Reduce。这就类似于多阶的归并排序了。具体会有多少重,就看数据量了。
reduce一定要能被反复调用,不论是映射环节还是前一个简化环节。所以reduce返回的文档必须能作为reduce的第二个参数的一个元素。
(当书写Map函数时,emit的第二个参数组成数组成了reduce函数的第二个参数,而Reduce函数的返回值,跟emit函数的第二个参数形式要一致,多个reduce函数的返回值可能会组成数组作为新的第二个输入参数再次执行Reduce操作。)
MapReduce函数的参数列表如下:
db.runCommand(
{ mapreduce : <collection>,
map : <mapfunction>,
reduce : <reducefunction>
[, query : <query filter object>]
[, sort : <sort the query. useful for optimization>]
[, limit : <number of objects to return from collection>]
[, out : <output-collection name>]
[, keeptemp: <true|false>]
[, finalize : <finalizefunction>]
[, scope : <object where fields go into javascript global scope >]
[, verbose : true]
}
);
或者这么写:
db.collection.mapReduce(
<map>,
<reduce>,
{
<out>,
<query>,
<sort>,
<limit>,
<keytemp>,
<finalize>,
<scope>,
<jsMode>,
<verbose>
}
)
执行MapReduce函数返回的文档结构如下:
{ result : <collection_name>,
timeMillis : <job_time>,
counts : {
input : <number of objects scanned>,
emit : <number of times emit was called>,
output : <number of items in output collection>
} ,
ok : <1_if_ok>,
[, err : <errmsg_if_error>]
}
java代码执行MapReduce的方法:
标签:style blog http color io os 使用 java ar
原文地址:http://www.cnblogs.com/HuiLove/p/3981775.html