使用Python中的google.cloud.bigquery写入bigQuery时,必需参数丢失错误

pyt*_*oob 1 google-analytics google-analytics-api python-2.7 google-bigquery google-cloud-platform

我正在使用Python 2.7中的以下代码片段向bigQuery加载新行分隔JSON:

from google.cloud import bigquery
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

bigquery_client = bigquery.Client()
dataset = bigquery_client.dataset('testGAData')
table_ref = dataset.table('gaData')
table = bigquery.Table(table_ref)

with open('gaData.json', 'rb') as source_file:
    job_config = bigquery.LoadJobConfig()
    job_config.source_format = 'NEWLINE_DELIMITED_JSON'
    job = bigquery_client.load_table_from_file(
        source_file, table, job_config=job_config)
Run Code Online (Sandbox Code Playgroud)

它返回以下错误:

File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/google/cloud/bigquery/client.py", line 897, in load_table_from_file
    raise exceptions.from_http_response(exc.response)
google.api_core.exceptions.BadRequest: 400 POST https://www.googleapis.com/upload/bigquery/v2/projects/test-project-for-experiments/jobs?uploadType=resumable: Required parameter is missing
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?我怎样才能解决这个问题?还有其他人遇到过类似的问题吗?提前致谢.编辑:添加最后一段,包括python导入并更正缩进.

Ted*_*ddy 8

初始代码观察到的问题

  • 您缺少表格的架构.你可以使用job_config.autodetect = Truejob_config.schema = [bigquery.SchemaField("FIELD NAME", "FIELD TYPE")].

  • 从文档中,您应该设置job_config.source_format = `bigquery.SourceFormat.NEWLINE_DELIMITED_JSON`JSON文件源

  • 您应该将table_ref变量作为参数传递,而不是将table变量传递给bigquery_client.load_table_from_file(source_file, table, job_config=job_config)

链接到文档

工作守则

以下代码适合我.我正在使用python 3和google-cloud-bigquery v1.5

from google.cloud import bigquery

client = bigquery.Client()
dataset_id, table_id = "TEST_DATASET", "TEST_TABLE"
data_ref = client.dataset(dataset_id)
table_ref = data_ref.table(table_id)
file_path = "path/to/test.json"

job_config = bigquery.LoadJobConfig()
job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
#job_config.autodetect = True
job_config.schema = [bigquery.SchemaField("Name", "STRING"), bigquery.SchemaField("Age", "INTEGER")]

with open(file_path, 'rb') as source_file:
    job = client.load_table_from_file(source_file, table_ref, location='US', job_config=job_config)

job.result()

print('Loaded {} rows into {}:{}.'.format(job.output_rows, dataset_id, table_id))
Run Code Online (Sandbox Code Playgroud)

产量

>> Loaded 2 rows into TEST_DATASET:TEST_TABLE.