incubator-couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Matthieu Rakotojaona <matthieu.rakotoja...@gmail.com>
Subject Re: what's the order of docs/keys going into reduce func?
Date Sat, 22 Sep 2012 20:28:09 GMT
I think you shouldn't rely on the order in which your keys and values
are passed to your reduce function, because there is no way to predict
it. Plus, the query might run any number of rereduce steps.

I propose the following :

map: func(doc){
  if (doc.type == 'lamp'){
    if (typeof doc.on == "undefined") {
      emit([doc.name, doc.seq],null);
    }
  }
}

fun(key, value, rereduce) {

  last_state_hash = {}

  // last_state_hash will look like {"a": 7, "b": 3, "c":12}

  if (rereduce == false) {

    // key is an array that looks like
    // [
    //  [["a",1],<someid1>],
    //  [["a",2],<someid2>],
    //  [["b",7],<someid3>]
    // ]
    //
    // value is an array of null (this is what we emitted)

    for (var i = 0; i < key.length; i++){
      name = key[i][0][0];
      seq = key[i][0][1];

      if (typeof(last_state_hash[name]) == 'undefined' ||
last_state_hash[name] < seq) {
        last_state_hash[name] = seq
      }
    }

  } else {

    // key is null for a rereduce
    // value is an array of state hashes as defined before

    for (var i = 0; i < value.length; i++) {

      current_state_hash = value[i];

      for (var name in current_state_hash){
        if (current_state_hash.hasOwnProperty(name)){

          if (typeof(last_state_hash[name]) == 'undefined' ||
              last_state_hash[name] < current_state_hash[name]) {
            last_state_hash[name] = current_state_hash[name]
          }

        }
      }

    }
  }

  return last_state_hash;

}

Beware of the comparison !

-- 
Matthieu RAKOTOJAONA

Mime
View raw message