0
0
mirror of https://github.com/mongodb/mongo.git synced 2024-11-30 17:10:48 +01:00
mongodb/shell/mr.js

96 lines
2.1 KiB
JavaScript
Raw Normal View History

2009-10-07 18:57:45 +02:00
// mr.js
MR = {};
MR.init = function(){
$max = 0;
$arr = [];
emit = MR.emit;
$numEmits = 0;
2009-10-15 17:26:51 +02:00
$numReduces = 0;
$numReducesToDB = 0;
2009-10-07 18:57:45 +02:00
gc(); // this is just so that keep memory size sane
}
MR.cleanup = function(){
MR.init();
gc();
}
MR.emit = function(k,v){
$numEmits++;
2009-11-04 20:48:36 +01:00
var num = nativeHelper.apply( get_num_ , [ k ] );
2009-10-07 18:57:45 +02:00
var data = $arr[num];
if ( ! data ){
data = { key : k , values : new Array(1000) , count : 0 };
2009-10-07 18:57:45 +02:00
$arr[num] = data;
}
data.values[data.count++] = v;
$max = Math.max( $max , data.count );
2009-10-07 18:57:45 +02:00
}
MR.doReduce = function( useDB ){
2009-10-15 17:26:51 +02:00
$numReduces++;
if ( useDB )
$numReducesToDB++;
2009-10-07 18:57:45 +02:00
$max = 0;
for ( var i=0; i<$arr.length; i++){
var data = $arr[i];
if ( ! data )
continue;
if ( useDB ){
var x = tempcoll.findOne( { _id : data.key } );
if ( x ){
data.values[data.count++] = x.value;
2009-10-07 18:57:45 +02:00
}
}
var r = $reduce( data.key , data.values.slice( 0 , data.count ) );
2009-10-09 01:45:49 +02:00
if ( r && r.length && r[0] ){
2009-10-07 18:57:45 +02:00
data.values = r;
data.count = r.length;
2009-10-07 18:57:45 +02:00
}
else{
data.values[0] = r;
data.count = 1;
2009-10-07 18:57:45 +02:00
}
$max = Math.max( $max , data.count );
2009-10-07 18:57:45 +02:00
if ( useDB ){
if ( data.count == 1 ){
2009-10-07 18:57:45 +02:00
tempcoll.save( { _id : data.key , value : data.values[0] } );
}
else {
tempcoll.save( { _id : data.key , value : data.values.slice( 0 , data.count ) } );
2009-10-07 18:57:45 +02:00
}
}
}
}
MR.check = function(){
if ( $max < 2000 && $arr.length < 1000 ){
return 0;
}
MR.doReduce();
if ( $max < 2000 && $arr.length < 1000 ){
return 1;
}
MR.doReduce( true );
$arr = [];
$max = 0;
reset_num();
gc();
return 2;
}
MR.finalize = function(){
tempcoll.find().forEach(
function(z){
z.value = $finalize( z._id , z.value );
tempcoll.save( z );
}
);
}