【发布时间】:2020-06-22 14:43:21
【问题描述】:
我有一个已经存在的表,其架构如下:
{
"schema": {
"fields": [
{
"mode": "required",
"name": "full_name",
"type": "string"
},
{
"mode": "required",
"name": "age",
"type": "integer"
}]
}
}
它已经包含以下条目:
{'full_name': 'John Doe',
'age': int(33)}
我想插入带有新字段的新记录,并让加载作业在加载时自动添加新列。新格式如下所示:
record = {'full_name': 'Karen Walker',
'age': int(48),
'zipcode': '63021'}
我的代码如下:
from google.cloud import bigquery
client = bigquery.Client(project=projectname)
table = client.get_table(table_id)
config = bigquery.LoadJobConfig()
config.autoedetect = True
config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
config.write_disposition = bigquery.WriteDisposition.WRITE_APPEND
config.schema_update_options = [
bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION,
]
job = client.load_table_from_json([record], table, job_config=config)
job.result()
这会导致以下错误:
400 提供的架构与表 my_project:my_dataset:mytable 不匹配。字段年龄已将模式从 REQUIRED 更改为 NULLABLE
我可以通过更改config.schema_update_options 来解决此问题,如下所示:
bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION,
bigquery.SchemaUpdateOption.ALLOW_FIELD_RELAXATION
]
这允许我插入新记录,并将 zipcode 添加到架构中,但它会导致 full_name 和 age 变为 NULLABLE,这不是我想要的行为。有没有办法防止模式自动检测更改现有列?
【问题讨论】:
-
JL 我只是尝试更改为
config.autodetect = False,但这并没有影响错误。 -
JL,没有 ALLOW_FIELD_RELAXATION 我得到
Field age has changed mode from REQUIRED to NULLABLE错误如上所述。