Reputation: 874
I have created a nested table in bigQuery and I would like to insert values into this table.
I know normally we can perform as below:
INSERT INTO `tablename`(webformID,visitID,visitorID,loginID,mycat,country,webformData) VALUES ('1',2,'3','4','5','6',[STRUCT('key2','b'),('k3','c'),('k4','d')])
where webform data is a nested column.
However, in python, how can we do this?
I can create a list as follows: ["STRUCT('key2','b')",('k3','c')]
but the 0th index is a problem while trying to insert.
Please advice Thank you
Upvotes: 3
Views: 2170
Reputation: 1301
You can insert data in the same order than the table was created.
Follow an example:
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)
Let me know if it helps!
Upvotes: 3