簡體   English   中英

BigQuery 架構表到 json 和 Python

[英]BigQuery schema table to json with Python

我需要這個 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
   })

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

感謝您的回復,祝您有美好的一天。

只需使用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())

和 output:

[
  {
    "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"
  }
]

這與使用命令時顯示的 output 相同:bq show --format=prettyjson bigquery-public-data.samples.wikipedia | jq '.schema.fields' :bq show --format=prettyjson bigquery-public-data.samples.wikipedia | jq '.schema.fields'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM