通过Python API V2在Google BigQuery中创建新表时缺少参数

2024-05-23 22:51:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用BigQuery的Python API创建新表:

bigquery.tables().insert(
    projectId="xxxxxxxxxxxxxx",
    datasetId="xxxxxxxxxxxxxx", 
    body='{
        "tableReference": {
            "projectId":"xxxxxxxxxxxxxx", 
            "tableId":"xxxxxxxxxxxxxx", 
            "datasetId":"accesslog"},
        "schema": {
            "fields": [
                {"type":"STRING", "name":"ip"},
                {"type":"TIMESTAMP", "name":"ts"},
                {"type":"STRING", "name":"event"},
                {"type":"STRING", "name":"id"},
                {"type":"STRING","name":"sh"},
                {"type":"STRING", "name":"pub"},
                {"type":"STRING", "name":"context"},
                {"type":"STRING", "name":"brand"},
                {"type":"STRING", "name":"product"}
            ]
        }
    }'
).execute()

我得到的错误是:

^{pr2}$

我认为只要在https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/python/latest/bigquery_v2.tables.html#insert上有文档记录,所有必需的参数都包括在内

少了什么?在


Tags: nameapitablesstringtypebodybigqueryv2
2条回答

可能太晚了,但问题是body参数必须是dictionary而不是字符串。在

tables.insert唯一需要的参数是tableReference,它必须有tableIddatasetId和{}字段。我认为实际的问题可能是在传递JSON字符串时,只需传递一个带有值的dict。例如,以下代码用于创建表(注意,dataset_ref是一个Python技巧,用于将内容复制到命名参数):

project_id = <my project>
dataset_id = <my dataset>
table_id = 'table_001'
dataset_ref = {'datasetId': dataset_id,
               'projectId': project_id}
table_ref = {'tableId': table_id,
             'datasetId': dataset_id,
             'projectId': project_id}
table = {'tableReference': table_ref}
table = bigquery.tables().insert(
    body=table, **dataset_ref).execute(http)

相关问题 更多 >