python - 如何将值插入到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 个索引是一个问题。
请指教 谢谢
解决方案
您可以按照与创建表相同的顺序插入数据。
举个例子:
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)
让我知道它是否有帮助!
推荐阅读
- javascript - 有没有办法从应用脚本中的 graphql API 获取数据?
- c# - 复制和重命名目录
- r - 使用 dplyr 检查每行中的多个变量(列)的值
- xcode - Xcode 无法安装在“macOS Sierra”上,因为需要 macOS 版本 10.14.3 或更高版本
- python - 我的用例中的 if-else 语句有问题
- sql - BIGQUERY:如何查询滚动的每月活跃用户/流失用户
- javascript - 从 Google Cloud Functions 发送 HTTP 请求是否有请求数量限制?
- javascript - 如何使用 src(裁剪)编辑 javascript 图像对象的 x1 y1 x2 y2
- c# - 如何将 DbContext 注入 NRules 类构造函数?
- java - Discord Bot 不会删除消息(带有 JDA API 的 Eclipse IDE Java)