【问题标题】:How to download large number of documents from Google cloud Firestore?如何从 Google Cloud Firestore 下载大量文档?
【发布时间】:2019-06-21 09:36:33
【问题描述】:

我在 Google Cloud Firestore 中有一个集合 data。这个集合有超过 200K 的文档。我想将每个文档作为一行导出到文件中。

我创建了一个适用于 50K 行的脚本。之后它崩溃并出现以下异常。如何获取所有文件?

我看到了一个叫做偏移的东西,但不确定它对我的情况有帮助。

代码片段:

from google.cloud import firestore
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"


db = firestore.Client()
col = db.collection(u'data')
docs = col.get()

with open('data.bak', 'a') as f:
    for doc in docs:
        f.write(u'{} => {}'.format(doc.id, doc.to_dict()))
        f.write('\n')

例外:

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "down_db.py", line 13, in <module>
    for doc in docs:
  File "/usr/local/lib/python3.6/dist-packages/google/cloud/firestore_v1beta1/query.py", line 744, in get
    for index, response_pb in enumerate(response_iterator):
  File "/usr/local/lib/python3.6/dist-packages/google/api_core/grpc_helpers.py", line 81, in next
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 The datastore operation timed out, or the data was temporarily unavailable.

【问题讨论】:

  • 以更小的块加载数据怎么样?
  • 我不是在向 Firestore 插入数据,而是在下载它。我无法控制限制数据或 where 子句。
  • 这也是我所说的,以较小的块下载数据。哦,你有。签出this
  • 谢谢@AlexMamo,我会试试的。稍后我会尝试query cursors

标签: google-cloud-platform google-cloud-firestore google-cloud-datastore


【解决方案1】:

Cloud Firestore python 客户端对get() 有 20 秒的超时。尝试分解工作或尝试获取所有文档引用然后迭代。

docs = [snapshot.reference for snapshot in col.get()]
for doc in docs:
        ...

Github issue regarding timeout

【讨论】:

    【解决方案2】:

    我认为还有另一种方法可以使用 gcloud 命令行工具,这将需要您使用 Bucket 存储和 BigQuery,两者都很容易上手。

    1. 在终端中使用gcloud firetore export function 导出集合:
    gcloud beta firestore export gs://[BUCKET_NAME] --collection-ids=[COLLECTION_ID_1],[COLLECTION_ID_2]
    

    您的整个集合将被导出到 GCS 存储桶,数据格式与 Cloud Datastore 相同,因此可以通过 BigQuery 读取......

    1. GCS Bucket to Bigquery 加载数据,导出的 Firestore 集合将在 BigQuery 中作为表存在

    2. 使用 select * from [TABLE_NAME] 之类的内容从 BigQuery 查询表,然后 BigQuery 可以选择以 CSV 格式下载查询结果

    【讨论】:

      【解决方案3】:

      我创建了一个对 50K 行运行良好的脚本。

      这个限制正是 Firebase 的 number of documents that you can read on a project on the free/Spark plan。如果您的项目采用免费计划,则需要对其进行升级以每天阅读更多文档。

      【讨论】:

      • 感谢@Frank van Puffelen。我正在使用 Firestore 形式的 Google 云项目。其中有 300 美元的信用额度,我猜行限制不适用于 GCP 项目。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 2021-02-09
      • 2013-08-19
      • 2020-12-11
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      相关资源
      最近更新 更多