Javascript 查询集合中所有游戏结果的平均分数?
我的应用程序在一个名为Javascript 查询集合中所有游戏结果的平均分数?,javascript,database,firebase,google-cloud-firestore,Javascript,Database,Firebase,Google Cloud Firestore,我的应用程序在一个名为score的字段中存储最终分数在-30到+30之间的游戏结果。如何查询所有游戏结果的总体平均值?简单解决方案 如果您知道正在写入的游戏结果的数量最多为每秒一次,那么您可以使用云函数更新单独的文档平均/分数。对于每个游戏结果添加,如果文档不存在,则将名为count的字段设置为1,并将名为score的字段设置为游戏分数。如果文档确实存在,请将1添加到名为count的字段中,并将分数添加到名为score的字段中 现在,要查询平均分数,只需阅读average/score并将scor
score
的字段中存储最终分数在-30到+30之间的游戏结果。如何查询所有游戏结果的总体平均值?简单解决方案
如果您知道正在写入的游戏结果的数量最多为每秒一次,那么您可以使用云函数更新单独的文档平均/分数
。对于每个游戏结果添加,如果文档不存在,则将名为count
的字段设置为1,并将名为score
的字段设置为游戏分数。如果文档确实存在,请将1
添加到名为count
的字段中,并将分数添加到名为score
的字段中
现在,要查询平均分数,只需阅读average/score
并将score
除以count
可扩展解决方案
如果您怀疑或知道正在写入的游戏结果数将超过每秒一次,则需要应用简单解决方案的分布式计数器样式
一般文档的数据模型将使用子集合,如下所示:
// average/score
{
"num_shards": NUM_SHARDS,
"shards": [subcollection]
}
// average/score/shards/${NUM}
{
"count": 115,
"score": 1472
}
要使更新代码更加精简,可以首先使用以下命令初始化这些碎片:
// ref points to db.collection('average').doc('score')
function createAverageAggregate(ref, num_shards) {
var batch = db.batch();
// Initialize the counter document
batch.set(ref, { num_shards: num_shards });
// Initialize each shard with count=0
for (let i = 0; i < num_shards; i++) {
let shardRef = ref.collection('shards').doc(i.toString());
batch.set(shardRef, { count: 0, count: 0 });
}
// Commit the write batch
return batch.commit();
}
然后可以通过以下方法获得平均值:
// ref points to db.collection('average').doc('score')
function getAverage(ref) {
// Sum the count and sum the score of each shard in the subcollection
return ref.collection('shards').get().then(snapshot => {
let total_count = 0;
let total_score = 0;
snapshot.forEach(doc => {
total_count += doc.data().count;
total_score += doc.data().score;
});
return total_score / total_count;
});
}
在这个系统中,您可以达到的写入速率是每秒NUM_个碎片,因此需要进行相应的计划。注意:你可以从小处开始,轻松增加碎片的数量。只需创建一个新版本的createAverageAggregate
,首先初始化新的碎片,然后更新num_碎片设置以匹配,从而增加碎片的数量。这应该由updateAverage
和getAverage
函数自动获取
// ref points to db.collection('average').doc('score')
function getAverage(ref) {
// Sum the count and sum the score of each shard in the subcollection
return ref.collection('shards').get().then(snapshot => {
let total_count = 0;
let total_score = 0;
snapshot.forEach(doc => {
total_count += doc.data().count;
total_score += doc.data().score;
});
return total_score / total_count;
});
}