使用Google BigQuery客户端API加载JSON文件到BigQuery

6 投票
1 回答
2638 浏览
提问于 2025-04-18 15:25

有没有办法通过Google BigQuery客户端API,从本地文件系统加载一个JSON文件到BigQuery?

我找到的所有选项有:

1- 一条一条地流式传输记录。

2- 从GCS(Google云存储)加载JSON数据。

3- 使用原始的POST请求来加载JSON(也就是说,不通过Google客户端API)。

1 个回答

3

我猜因为你提到了python,所以你想用python来做这个。这里有一个加载数据的示例,可以在这里找到,它是从本地文件加载数据的(它使用的是CSV格式,但很容易改成JSON格式……在同一个目录下还有另一个JSON的示例)。

基本的流程是:

# Load configuration with the destination specified.
load_config = {
  'destinationTable': {
    'projectId': PROJECT_ID,
    'datasetId': DATASET_ID,
    'tableId': TABLE_ID
  }
}

load_config['schema'] = {
  'fields': [
    {'name':'string_f', 'type':'STRING'},
    {'name':'boolean_f', 'type':'BOOLEAN'},
    {'name':'integer_f', 'type':'INTEGER'},
    {'name':'float_f', 'type':'FLOAT'},
    {'name':'timestamp_f', 'type':'TIMESTAMP'}
  ]
}
load_config['sourceFormat'] = 'NEWLINE_DELIMITED_JSON'

# This tells it to perform a resumable upload of a local file
# called 'foo.json' 
upload = MediaFileUpload('foo.json',
                         mimetype='application/octet-stream',
                         # This enables resumable uploads.
                         resumable=True)

start = time.time()
job_id = 'job_%d' % start
# Create the job.
result = jobs.insert(
  projectId=project_id,
  body={
    'jobReference': {
      'jobId': job_id
    },
    'configuration': {
      'load': load
    }
  },
  media_body=upload).execute()

 # Then you'd also want to wait for the result and check the status. (check out
 # the example at the link for more info).

撰写回答