首页 > 解决方案 > 如何将值插入到python中的嵌套表中?

问题描述

我在 bigQuery 中创建了一个嵌套表,我想将值插入到该表中。

我知道通常我们可以执行如下操作:

INSERT INTO `tablename`(webformID,visitID,visitorID,loginID,mycat,country,webformData) VALUES ('1',2,'3','4','5','6',[STRUCT('key2','b'),('k3','c'),('k4','d')])

其中 webform 数据是一个嵌套列。

但是,在python中,我们怎么能做到这一点?

我可以按如下方式创建一个列表:["STRUCT('key2','b')",('k3','c')]但是尝试插入时第 0 个索引是一个问题。

请指教 谢谢

标签: pythongoogle-cloud-platformgoogle-bigquery

解决方案


您可以按照与创建表相同的顺序插入数据。

举个例子:

from google.cloud import bigquery

client = bigquery.Client.from_service_account_json(JSON_FILE_NAME)
dataset_id = 'test'  # replace with your dataset ID
table_id = 'tablek1'  # replace with your table ID

schema = [
        bigquery.table.SchemaField('column1', 'STRING', mode='REQUIRED'),
        bigquery.table.SchemaField('parent', 'RECORD', mode='REQUIRED', fields = [
            bigquery.table.SchemaField('children1', 'STRING', mode='NULLABLE'),
            bigquery.table.SchemaField('children2', 'INTEGER', mode='NULLABLE')])
    ]

dataset_ref = bigquery.Dataset(client.dataset(dataset_id))
table_ref = dataset_ref.table(table_id)
table = bigquery.Table(table_ref, schema=schema)
table = client.create_table(table)  # API request

# IF YOU NEED GET THE TABLE
# table_ref = client.dataset(dataset_id).table(table_id) 
# table = client.get_table(table_ref)  # API request

rows_to_insert = [
    (
        "test 1", dict(children1 = 'test', children2 = 29 ),     
    )
]

errors = client.insert_rows(table, rows_to_insert)  # API request
print(errors)

让我知道它是否有帮助!


推荐阅读