我正在尝试从 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/