我在 Firebase 的 Cloud Firestore 数据库中有一个集合,其中包含如下子集合:
myCollection
doc1
statistics
doc1
doc2
doc3
doc2
statistics
doc1
doc2
doc3
statistics
doc1
doc2
doc3
doc4
doc4
statistics
等等。
例如,根据查询,我可能从集合中提取 doc1、doc2 和 doc4。现在,对于其中每一个,我需要查询它们各自的子集合以获取相关统计信息。
到目前为止,我在 AngularJS 应用程序中的解决方案是:
/**
* Gets aggregate views for queried docs.
* @param {![firebase.firestore.DocumentSnapshot]} docs - the queried documents
*/
$scope.getTotalViews = (docs) => {
let promises = [];
docs.forEach(doc => {
promises.push($scope.getTotalDocumentViews(doc.id));
});
$q.all(promises).then(totalViewsArray => {
// TODO: Sum the array to get aggregate views for queried documents
// Only outputs some of the time
console.log(totalViewsArray);
});
};
/**
* Gets all view statistics from a given document's subcollection.
*/
$scope.getTotalDocumentViews = (id) => {
let deferred = $q.defer();
firebase.firestore().collection("myCollection").doc(id).collection("statistics").where("type", "==", "view").get().then(snapshot => {
deferred.resolve(snapshot.size);
});
return deferred.promise;
};
我遇到的问题是,由于 myCollection 上的查询可能返回许多文档,因此循环遍历所有这些文档并查询它们的子集合似乎效率非常低。不仅如此,虽然上面的代码有时会成功,但很多时候它会抛出错误:
Uncaught (in promise) Error: transaction closed
我还尝试在事务中执行多个子集合查询,但这效果不佳,因为我不是只检索一个文档,而是从子集合中查询可能数百个文档。
如何有效地查询某些多个文档集的子集合?
最佳答案
我认为这同样适用于大多数其他 NoSQL 数据库(当然还有 Firebase 实时数据库):如果您希望能够有效地从数据库中获取某些内容的计数,您应该将该计数存储为属性并不断更新它(在这种情况下) View 发生。尝试阅读数百份文档只是为了确定其数量是无法扩展的。
因此,请考虑向每个文档添加一个 view_count
属性,并在记录 View 时增加该属性(可能使用 transaction )。
关于angularjs - 如何在 Firebase Cloud Firestore 中高效执行多次读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47255563/