Cha*_*how 3 python google-bigquery
相关问题:Bigquery 使用 BQ 命令行工具将列添加到表架构
我想使用 BigQuery Python API在 BigQuery 中向现有表添加新列(更新现有表的架构)。
但是我的代码似乎不起作用。
这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
它返回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()
Run Code Online (Sandbox Code Playgroud)
而且,无法为现有行(表)设置新列的值。感谢您的Mikhail Berlyant建议,为现有行设置值的方法是为具有值的新列创建一个单独的表,并将现有表与该表连接以替换旧的架构表