如何在python中向嵌套表中插入值?

2024-09-30 22:22:22 发布

您现在位置: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个索引在尝试插入时出现问题。在

请指教 谢谢你


Tags: 情况bigquerycountrystructinsertkey2intotablename
1条回答
网友
1楼 · 发布于 2024-09-30 22:22:22

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

举个例子:

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)

如果有帮助就告诉我!在

相关问题 更多 >