Last active
December 3, 2019 14:57
-
-
Save radleta/ad6fd611bbb4e7e210c72770cf756cba to your computer and use it in GitHub Desktop.
The map and reduce functions for Couchbase view to count the number of documents set to expire on a specific number of days from today by their key prefix with two levels.
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
function (keys, values, rereduce) { | |
var result = {}; | |
if (rereduce) { | |
values.forEach(function (firstIndex) { | |
for (var firstKey in firstIndex) { | |
// try to get the result associated with this key | |
var firstResult = result[firstKey]; | |
// when it doesn't exist then init default | |
if (!firstResult) { | |
firstResult = {}; | |
result[firstKey] = firstResult; | |
} | |
// get this result | |
var secondIndex = firstIndex[firstKey]; | |
// merge all values | |
for (var secondKey in secondIndex) { | |
firstResult[secondKey] = (firstResult[secondKey] || 0) + secondIndex[secondKey]; | |
} | |
} | |
}); | |
} else { | |
for (var i = 0; i < keys.length; i++) { | |
var key = keys[i]; | |
var value = values[i]; | |
var firstResult = result[key]; | |
if (!firstResult) { | |
firstResult = {}; | |
result[key] = firstResult; | |
} | |
var secondResult = firstResult[value]; | |
if (!secondResult) { | |
firstResult[value] = 1; | |
} else { | |
firstResult[value] = secondResult + 1; | |
} | |
} | |
} | |
return result; | |
} |
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
function (doc, meta) { | |
var firstSeparator = meta.id.indexOf('_'); | |
var secondSeparator = meta.id.indexOf('_', firstSeparator+1); | |
var separatorAt = Math.max(firstSeparator, secondSeparator); | |
var keyPrefix = meta.id.substring(0, separatorAt); | |
var expiresInDays; | |
if (meta.expiration > 0) { | |
expiresInDays = Math.round((meta.expiration - (new Date().getTime()/1000)) / 86400); | |
} else { | |
expiresInDays = -1; | |
} | |
emit(keyPrefix, expiresInDays); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment