相关问题:Bigquery add columns to table schema using BQ command line tools
我想使用 BigQuery 在 BigQuery 中向现有表添加新列(更新现有表的架构)Python API .
但是我的代码似乎不起作用。
这是我的代码:
flow = flow_from_clientsecrets('secret_key_path', scope='my_scope')
storage = Storage('CREDENTIAL_PATH')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, tools.argparser.parse_args([]))
http = httplib2.Http()
http = credentials.authorize(http)
bigquery_service = build('bigquery', 'v2', http=http)
tbObject = bigquery_service.tables()
query_body = {'schema': {'name':'new_column_name', 'type':'STRING'}}
tbObject.update(projectId='projectId', datasetId='datasetId', tableId='tableId', body=query_body).execute()
它返回Provided schema doesn't match existing table's schema 错误。 谁能给我一个有效的 Python 示例? 非常感谢!
请您参考如下方法:
根据 Mikhail Berlyant 评论,我必须将带有新字段(列)的现有表架构传递给 update() 方法以更新现有表的架构。
下面给出一个python代码示例:
...
tbObject = bigquery_service.tables()
# get current table schema
table_data = tbObject.get(projectId=projectId, datasetId=datasetId, tableId=tableId).execute()
schema = table_data.get('schema')
new_column = {'name': 'new_column_name', 'type': 'STRING'}
# append new field to current table's schema
schema.get('fields').append(new_column)
query_body = {'schema': schema}
tbObject.update(projectId='projectId', datasetId='datasetId', tableId='tableId', body=query_body).execute()
而且,无法为现有行(表)设置新列的值。感谢 Mikhail Berlyant 建议,为现有行设置值的方法是为具有值的新列创建一个单独的表,并将现有表与该表连接以替换旧模式表
