Cloud Firestore - 使用循环getDocument请求缓慢执行(500多个文档)(Swift)

时间:2017-10-12 10:59:12

标签: ios swift loops firebase google-cloud-firestore

我编写了一个从API调用中提取信息的函数,解析生成的JSON,遍历每个结果项,然后在以下View Controller上显示此信息。在这个循环中,我必须从Firestore数据库中提取每个项目的信息。

我正在使用Swift 4& Firestore 0.8.0

以下代码是我目前使用的代码,它考虑了我们的数据库中是否存在某个项目,只有在所有Firestore请求都已完成时才会出现segue:

for item in results {
    dispatch.enter()
    //Main loop code for processing the API Call & pulling the document ID for this item

    let docRef = db.collection("collection").document(documentID)
    docRef.getDocument { (document, error) in
        if (document?.exists ?? false), error == nil {
            if let document = document {
                let data = document.data()
                print("EXISTS")
                //do things
                dispatch.leave()
            } else {
                print("Document does not exist")
                dispatch.leave()
            }
        } else {
            print("DOES NOT EXIST") 
            //do other things
            dispatch.leave()
        }
    }
}
dispatch.notify(queue: .main) {
    //perform a segue to the data display VC
}

(代码是使用此问题编写的 - > Crashes with Firestore,如果文档不存在于您的收藏中,目前Firestore最初不会返回nil值

我遇到的问题是此功能最终需要几分钟才能完成。是否有更快的方式来执行此循环文档请求?这只是测试版的表现吗?

我们的Firestore集合最终将拥有1,000,000多个文档,从每个文档中提取的字段都是嵌套的,如下所示:

collection {
    document {
        object {
           item1: data to pull
           item2: data to pull
           ...etc
        }
    }
}

任何帮助将不胜感激!

更新&结论

好像我正在采取相反的方法!由于我们数据库的性质意味着我们存储了API数据的所有文档,因此我可以在Firestore数据库上执行单个查询以限制数据,然后强制API调用仅返回基于初始查询找到的文档的结果。这样就无需检查我们的数据库中是否存在任何API调用结果文档!易peasy!

1 个答案:

答案 0 :(得分:1)

我认为问题是您要向数据库发出500多个单独的提取请求。无论如何,这可能会很慢。

我会寻找将这些数据放入集合中然后查询集合以获取所需文档的方法。这至少可以让你通过一次调用获得这些数据(或者更好的是,如果你不需要同时获得所有500个文档,那么获取分页数据)

相关问题