可以通过在JSON数据中添加默认值,并使用BigQuery Schema定义来指定缺少值时要使用的默认值。
以下是一个使用Python代码的示例:
from google.cloud import bigquery
# 定义JSON数据中的架构和默认值
json_schema = [
{"name": "id", "type": "integer", "mode": "required"},
{"name": "name", "type": "string", "mode": "nullable", "default": "unknown"},
{"name": "age", "type": "integer", "mode": "nullable", "default": 18},
{"name": "address", "type": "string", "mode": "nullable", "default": "unknown"}
]
# 将JSON数据和架构加载到BigQuery表
client = bigquery.Client()
table_ref = client.dataset('my_dataset').table('my_table')
job_config = bigquery.LoadJobConfig(
schema=json_schema,
source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
)
with open('my_data.json', 'rb') as json_file:
job = client.load_table_from_file(json_file, table_ref, job_config=job_config)
job.result()
这个示例指定了一个JSON架构,其中包含名称,类型,模式和默认值,然后通过将JSON数据和架构加载到BigQuery表来使用此架构。在JSON数据中缺少任何字段时,将自动使用指定的默认值。
请注意,如果JSON数据中提供了值,则该值将覆盖默认值。