使iPython BigQuery魔术函数SQL查询动态化



我在Jupyter中使用bigquery魔术函数,希望能够动态更改项目和数据集。例如

代替

%%bigquery table
SELECT * FROM `my_project.my_dataset.my_table`

我想要

project = my_project
dataset = my_dataset
%%bigquery table
'SELECT * FROM `{}.{}.my_table`'.format(project,dataset)

根据IPython Magics for BigQuery文档,不可能将项目或数据集作为参数传递;尽管如此,您可以使用BigQuery客户端库在Jupyter Notebook中执行此操作。

from google.cloud import bigquery
client = bigquery.Client()  
project = 'bigquery-public-data'
dataset = 'baseball'
sql ="""SELECT * FROM `{}.{}.games_wide` LIMIT 10"""
query=sql.format(project,dataset)
query_job = client.query(query)
print("The query data:")
for row in query_job:
# Row values can be accessed by field name or index.
print("gameId={}, seasonId={}".format(row[0], row["gameId"]))

我还建议您查看公共文档,了解如何在Jupyter笔记本中可视化BigQuery数据。

最新更新