如何通过 Python SDK 复制 BigQuery 视图



我有两个 BigQuery 项目,我想将视图从项目 1 复制到项目 2:

from google.cloud import bigquery
proj_1 = bigquery.Client.from_service_account_json(<path>, project='Project 1')
dataset_1 = proj_1.dataset(<dataset_name>)
view_1 = dataset_1.table(<view_name>)  # View to copy, already existing
proj_2 = bigquery.Client.from_service_account_json(<path>, project='Project 2')
dataset_2 = proj_2.dataset(<dataset_name>)
view_2 = dataset_2.table(<view_name>)  # Destination for copied view
# Start copy job like Google says
# https://cloud.google.com/bigquery/docs/tables#copyingtable

我收到以下错误:

RuntimeError: [{'message': 'Using table <project>:<dataset>.<view_name> is not allowed for this operation because of its type. Try using a different table that is of type TABLE.', 'reason': 'invalid'}]

我已经知道,如果我将属性设置为 view_queryview_2将被识别为视图。如果我手动设置它,它可以工作。但是第二个(自动化(解决方案没有,因为属性view_1.view_query始终None .

view_2.view_query = 'SELECT * FROM ...'  # works
view_2.view_query = view_1.view_query    # Won't work, because view_1.view_query is always None

如何访问view_1的查询?

view_1.reload()调用加载属性view_query

见 https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery-usage.html

所以

view_1.reload()
view_2.view_query = view_1.view_query
view_2.create()  # No need for a copy job, because there is no data copied

现在就行了。

最新更新