【问题标题】:How do I perform multiple reads in Firebase Cloud Firestore efficiently?如何有效地在 Firebase Cloud Firestore 中执行多次读取?
【发布时间】:2018-04-25 14:49:39
【问题描述】:

我在 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

我还尝试在事务中执行多个子集合查询,但效果不佳,因为我不只检索一个文档,而是从子集合中查询可能数百个文档。

如何有效地查询一组多个文档的子集合?

【问题讨论】:

    标签: angularjs firebase google-cloud-firestore


    【解决方案1】:

    我认为这同样适用于大多数其他 NoSQL 数据库(当然还有 Firebase 实时数据库):如果您希望能够有效地从数据库中获取某些内容的计数,您应该将该计数存储为一个属性并不断更新它(在这种情况下)视图出现。试图阅读数百份文档只是为了确定它们的数量是无法扩展的。

    因此,请考虑为每个文档添加view_count 属性,并在记录视图时增加该属性(可能使用transaction)。

    【讨论】:

    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2019-10-22
    • 2020-11-08
    • 2021-06-19
    • 2022-12-03
    • 1970-01-01
    相关资源
    最近更新 更多