python 大查询|巨蟒|从BigQuery表中导出数据VIEW

qaxu7uf2  于 2023-02-28  发布在  Python
关注(0)|答案(2)|浏览(188)

这是一个简单的代码导出从Biq查询到谷歌存储,在CSV格式

def export_data():

  client = bigquery.Client()

  project = 'xxxxx'
  dataset_id = 'xxx'
  table_id = 'xxx'
  bucket_name = 'xxx'

  destination_uri = 'gs://{}/{}'.format(bucket_name, 'EXPORT_FILE.csv')
  dataset_ref = client.dataset(dataset_id, project=project)
  table_ref = dataset_ref.table(table_id)

  extract_job = client.extract_table(
      table_ref,
      destination_uri,
      # Location must match that of the source table.
      location='EU')  # API request
  extract_job.result()  # Waits for job to complete.

  print('Exported {}:{}.{} to {}'.format(
      project, dataset_id, table_id, destination_uri))

它可以完美地用于一般表格,但当我尝试从保存的表格VIEW导出数据时,它失败了,并出现以下错误:

BadRequest: 400 Using table xxx:xxx.xxx@123456 is not allowed for this operation because of its type. Try using a different table that is of type TABLE.

是否存在从表视图导出数据的方法?
我尝试实现的是,从BigQuery获取CSV格式的数据,并上传到Google分析产品数据

acruukt9

acruukt91#

大查询视图are subject to a few limitations

  • 不能运行从视图导出数据的BigQuery作业。

有超过10+个其他限制,我没有张贴在答案中,因为他们可能会改变。按照link阅读所有这些限制。
您需要查询视图并将结果写入目标表,然后在目标表上发出导出作业。

kkbh8khc

kkbh8khc2#

大约5年后,这可能对遇到同样问题的人有用。一个解决办法是查询视图并使用BigQuery创建的临时表进行导出,避免创建和删除临时表。
修改原始问题以使用临时表的代码:

def export_data():

  client = bigquery.Client()

  project = 'xxxxx'
  dataset_id = 'xxx'
  view_id = 'xxx'
  bucket_name = 'xxx'

  destination_uri = f'gs://{bucket_name}/EXPORT_FILE.csv'

  query = f"SELECT * FROM `{project}.{dataset_id}.{view_id}`"
  query_job = client.query(query)
  result = query_job.result()
  print(f"Reading {result.total_rows} rows from BigQuery")

  destination = query_job.destination
  destination_table = client.get_table(destination)

  extract_job = client.extract_table(
      destination_table,
      destination_uri,
      # Location must match that of the source table.
      location='EU')  # API request
  extract_job.result()  # Waits for job to complete.

  print(f'Exported {project}:{dataset_id}.{table_id} to {destination_uri}')

相关问题