Skip to content

Instantly share code, notes, and snippets.

@radleta
Last active December 2, 2019 15:58
Show Gist options
  • Save radleta/4d8e7dcbd161e2cee6c80f3f104527c8 to your computer and use it in GitHub Desktop.
Save radleta/4d8e7dcbd161e2cee6c80f3f104527c8 to your computer and use it in GitHub Desktop.
The map and reduce functions for a Couchbase view to show the stats on the size of the documents in a bucket grouped by the key prefix when it is either an underscore or colon.
function (doc, meta) {
// calculate the size of the document
var size;
if (meta.type == "json") {
size = JSON.stringify(doc).length;
} else if (meta.type == "base64") {
size = decodeBase64(doc).length;
}
// try to figure out the separator
// try underscore first
var firstSeparator = meta.id.indexOf('_');
// try colon second
firstSeparator = (firstSeparator > -1) ? firstSeparator : meta.id.indexOf(':');
// use the firstKeyPart when possible
if (firstSeparator > -1) {
var firstKeyPart = meta.id.substring(0, firstSeparator);
emit(firstKeyPart, size);
} else {
emit('n/a', size);
}
}
function (keys, values, rereduce) {
function createResult() {
return {
sum: 0,
cnt: 0,
avg: 0,
min: false,
max: false,
};
}
var result = {};
if (rereduce) {
values.forEach(function (v) {
for (var k in v) {
// try to get the result associated with this key
var keyResult = result[k];
// when it doesn't exist then init default
if (!keyResult) {
keyResult = createResult();
result[k] = keyResult;
}
// get this result
var valueResult = v[k];
// merge all values
keyResult.cnt += valueResult.cnt;
keyResult.sum += valueResult.sum;
keyResult.min = keyResult.min === false ? valueResult.min : Math.min(keyResult.min, valueResult.min);
keyResult.max = keyResult.max === false ? valueResult.max : Math.max(keyResult.max, valueResult.max);
}
});
} else {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = values[i];
// build the result for this key
var keyResult = createResult();
result[key] = keyResult;
// increment the values
keyResult.cnt++;
keyResult.sum += value;
keyResult.min = keyResult.min === false ? value : Math.min(keyResult.min, value);
keyResult.max = keyResult.max === false ? value : Math.max(keyResult.max, value);
}
}
// set the avg
for (var k in result) {
var keyResult = result[k];
keyResult.avg = keyResult.sum / keyResult.cnt;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment