python-3.x - Python BigQuery API - 获取表架构

标签 python-3.x google-cloud-platform google-bigquery google-cloud-datastore

我正在尝试从 bigquery 表中获取模式。给出一个示例代码,如

from google.cloud import bigquery
from google.cloud import storage

client =  bigquery.Client.from_service_account_json('service_account.json')

def test_extract_schema(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)  # API Request

    # View table properties
    print(table.schema)

if __name__ == '__main__':
    test_extract_schema(client)

这是返回值,如:
[SchemaField('word', 'STRING', 'REQUIRED', 'A single unique word (where whitespace is the delimiter) extracted from a corpus.', ()), SchemaField('word_count', 'INTEGER', 'REQUIRED', 'The number of times this word appears in this corpus.', ()), SchemaField('corpus', 'STRING', 'REQUIRED', 'The work from which this word was extracted.', ()), SchemaField('corpus_date', 'INTEGER', 'REQUIRED', 'The year in which this corpus was published.', ())]
我试图仅以类似的格式捕获模式的地方
'word' 'STRING','word_count' INTEGER'

有没有办法使用 API 调用或任何其他方法来获得它?

最佳答案

您可以随时获得 table.schema变量并对其进行迭代,因为该表是由 SchemaField 组成的列表值(value)观:

result = ["{0} {1}".format(schema.name,schema.field_type) for schema in table.schema]

相同数据集和表的结果:
['word STRING', 'word_count INTEGER', 'corpus STRING', 'corpus_date INTEGER']

关于python-3.x - Python BigQuery API - 获取表架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885946/

相关文章:

google-bigquery - 如何在不指定列名的情况下使用 bigquery 在表中的每一列上调用内置函数?

google-app-engine - Go 的 AppAssertionCredentials 在哪里?

python - 在 python psycopg2 中通过列名检索值

创建从字典键到它的值的所有组合的 Pythonic 方法

node.js - Google App Engine 部署文件太大

google-cloud-platform - Cloud ML Service 帐户无法访问 Cloud Storage 且未列在 IAM 和管理面板中

python-3.x - 为什么将字节传递给类 str 构造函数很特别?

python - 没有 Math 模块的 Python 3 中的 Ceil 和 floor 等效?

java - 使用 spring boot 从 Secret Manager GCP 获取值

Python 2.7 和 GCP 谷歌 BigQuery : Capturing file load errors?