【问题标题】:BigQuery schema table to json with Python使用 Python 将 BigQuery 架构表转换为 json
【发布时间】:2020-05-22 09:23:07
【问题描述】:

我需要这个 BigQuery bq show --format=prettyjson myproject:mydataset.mytable 的 Python 等效项。

有没有办法在 Python 中使用 BigQuery API 来做到这一点?

我在 Python 中试过这个:

view_ref = self._client.dataset(dataset.dataset_id).table(table.table_id)
table_obj = self._client.get_table(view_ref)

dict_schema = []
for schema_field in table_obj.schema:
    dict_schema.append({
        'name': schema_field.name,
        'mode': schema_field.mode,
        'type': schema_field.field_type
   })

它几乎可以工作;我只是没有嵌套模式字段/

感谢您的回复,祝您有美好的一天。

【问题讨论】:

    标签: python google-bigquery


    【解决方案1】:

    您可以简单地使用schema_to_json() 方法将您的表模式转换为json。它需要两个属性,分别是 schema_listdestination

    我使用带有嵌套数据的公共数据集来举例说明您的情况,并使用StringIO() 来展示架构的样子。

    from google.cloud import bigquery
    import io
    
    client = bigquery.Client()
    
    project = 'bigquery-public-data'
    dataset_id = 'samples'
    table_id = 'shakespeare'
    
    dataset_ref = client.dataset(dataset_id, project=project)
    table_ref = dataset_ref.table(table_id)
    table = client.get_table(table_ref)
    
    
    f = io.StringIO("")
    client.schema_to_json(table.schema, f)
    print(f.getvalue())
    

    还有输出:

    [
      {
        "description": "A single unique word (where whitespace is the delimiter) extracted from a corpus.",
        "mode": "REQUIRED",
        "name": "word",
        "type": "STRING"
      },
      {
        "description": "The number of times this word appears in this corpus.",
        "mode": "REQUIRED",
        "name": "word_count",
        "type": "INTEGER"
      },
      {
        "description": "The work from which this word was extracted.",
        "mode": "REQUIRED",
        "name": "corpus",
        "type": "STRING"
      },
      {
        "description": "The year in which this corpus was published.",
        "mode": "REQUIRED",
        "name": "corpus_date",
        "type": "INTEGER"
      }
    ]
    

    与使用命令!bq show --format=prettyjson bigquery-public-data:samples.wikipedia | jq '.schema.fields'时显示的输出相同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2015-11-27
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      相关资源
      最近更新 更多