【问题标题】:How to check if a dataset exists in BigQuery?如何检查 BigQuery 中是否存在数据集?
【发布时间】:2020-04-29 13:50:16
【问题描述】:

我们可以按如下方式启动 BigQuery 数据集:

dataset_ref = self.client.dataset(dataset_id=self.dataset_id)
dataset = bigquery.Dataset(dataset_ref)

如何检查此数据集是否已存在?当我查看数据集的属性时,它们似乎与存在的集合和不存在的集合重叠。

【问题讨论】:

  • 试试if dataset.createdif dataset.created is not None googleapis.dev/python/bigquery/latest/generated/…
  • 该选项存在延迟。基本上,填充该值最多需要几秒钟,如果不是几分钟的话。
  • 您能否尝试创建数据集并捕获已存在的异常?
  • 是的,除了Conflict(来自google.api_core.exceptions import Conflict),我可以捕捉到它,但我希望有一个更优雅的解决方案。此外,当您深入了解 google.cloud.bigquery.dataset 时,我没有看到任何有用的方法。
  • else dataset._properties.get("creationTime") 可能会为您节省几毫秒的时间。

标签: python google-bigquery


【解决方案1】:

docs 建议使用get_dataset 来确定数据集是否存在。

from google.cloud.exceptions import NotFound

dataset_id = "pigs_in_space"

try:
    client.get_dataset(dataset_id)  # Make an API request.
    print("Dataset {} already exists".format(dataset_id))
except NotFound:
    print("Dataset {} is not found".format(dataset_id))

【讨论】:

  • 这行得通,但问题是每次调用时都会记录一个错误。
【解决方案2】:

您可以使用 create_dataset 函数中的 exists_ok 参数忽略该错误。

# create dataset if not exists

self.client.create_dataset(dataset_id=self.dataset_id, exists_ok=True)

我在 Google 的 bigquery API repo 中找到了它。

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2020-12-13
    • 2015-04-28
    • 2016-07-28
    相关资源
    最近更新 更多