Pip*_*iks 2 javascript firebase firebase-realtime-database google-cloud-functions
最近Firebase推出了云功能。
就我而言,此功能对于计算数据库中的元素非常有用。
Firebase 发布了一个示例代码来计算元素,但我问自己一些有关大数据的问题。
在我们的示例中,我们认为需要计算帖子的点赞数。
在示例代码中,每次点赞时,该函数都会对当前帖子的所有点赞进行计数并更新计数。
您认为这是一个很好的大数据解决方案吗?(例如,如果我们有 100 万个赞)
先感谢您 !
同意函数示例中的代码对于大型数据集并不理想。
很长一段时间以来,我在计数器中使用了两步方法:
因此,情况 #2 与当前代码一样受内存限制。但情况#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());
});
}
});
Run Code Online (Sandbox Code Playgroud)
我还在回购协议的 PR 中提交了这个。