Created
May 15, 2012 13:30
-
-
Save adamlofts/2701794 to your computer and use it in GitHub Desktop.
"Table scan" CouchDB map-reduce.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Run a chained map reduce on a couchdb view | |
* | |
* @param db The db to use | |
* @param view The view name | |
* @param map_func The map function to use on the view results function({ key: , value: }) -> { key: , value: } | |
* @param config Standard jquery.couch.js config options | |
*/ | |
var chainCouch = (function() { | |
var cmp, | |
icmp; | |
cmp = function(keya, keyb) { | |
var ret = 0; | |
if (Array.isArray(keya)) { | |
$.each(keya, function(i, va) { | |
var vb = keyb[i]; | |
ret = cmp(va, vb); | |
if (ret !== 0) { | |
return false; | |
} | |
}); | |
if ((ret === 0) && (keya.length < keyb.length)) { | |
return -1; | |
} | |
return ret; | |
} | |
if (typeof(keya) == 'object') { | |
if (typeof(keyb) == 'object') { | |
return 0; | |
} | |
return 1; | |
} | |
if (typeof(keyb) == 'object') { | |
return -1; | |
} | |
if (keya < keyb) { | |
return -1; | |
} | |
if (keya > keyb) { | |
return 1; | |
} | |
return 0; | |
} | |
icmp = function(keya, keyb) { | |
return -cmp(keya, keyb); | |
} | |
return function(db, view, map_func, config) { | |
var startkey = config.startkey, | |
endkey = config.endkey, | |
is_reverse = config.descending, | |
c = cmp, | |
limit = config.limit; | |
if (is_reverse) { | |
c = icmp; | |
} | |
db.view(view, { | |
reduce: true, | |
group: true, | |
success: function(result) { | |
var mapped = $.map(result.rows, map_func), | |
sort_func; | |
// slice | |
mapped = $.map(mapped, function(row) { | |
var key = row.key; | |
if (c(startkey, key) > 0) { | |
return; | |
} | |
if (c(endkey, key) < 0) { | |
return; | |
} | |
return row; | |
}); | |
mapped.sort(function(rowa, rowb) { | |
return c(rowa.key, rowb.key); | |
}); | |
if (limit) { | |
mapped = mapped.slice(0, limit); | |
} | |
config.success({ rows: mapped }); | |
} | |
}); | |
}; | |
}()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment