最近 Firebase 介绍 Cloud Functions .
在我的案例中,此功能对于计算数据库中的元素非常有用。
Firebase 发布了一个 sample code to count elements但我会问自己一些关于大数据的问题。
在我们的示例中,我们认为我们需要计算帖子的点赞次数。
在示例代码中,在每个新点赞时,该函数都会计算当前帖子的所有点赞次数并更新计数。
您认为这是大数据的良好解决方案吗? (例如,如果我们有 100 万个赞)
提前致谢!
最佳答案
同意函数示例中的代码对于大型数据集来说并不理想。
很长一段时间以来,我在我的计数器中使用了两步法:
- 添加/删除子项时,增加/减少计数器
- 当计数器被删除时,重新计算所有 child (就像现在一样)
所以案例 #2 与当前代码一样是内存绑定(bind)的。但是案例 #1 会触发子写入,因此内存消耗要少得多。
代码:
// Keeps track of the length of the 'likes' child list in a separate property.
exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => {
var collectionRef = event.data.ref.parent;
var countRef = collectionRef.parent.child('likes_count');
return countRef.transaction(function(current) {
if (event.data.exists() && !event.data.previous.exists()) {
return (current || 0) + 1;
}
else if (!event.data.exists() && event.data.previous.exists()) {
return (current || 0) - 1;
}
});
});
// If the number of likes gets deleted, recount the number of likes
exports.recountlikes = functions.database.ref("/posts/{postid}/likes_count").onWrite((event) => {
if (!event.data.exists()) {
var counterRef = event.data.ref;
var collectionRef = counterRef.parent.child('likes');
return collectionRef.once('value', function(messagesData) {
return counterRef.set(messagesData.numChildren());
});
}
});
我还在 repo 的 PR 中提交了这个。
关于javascript - Firebase 函数,计算大数据的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727872/