Making iPython BigQuery Magic Function SQL query dynamic

2.2k Views Asked by At

I am using the bigquery magic function in Jupyter and would like to be able to dynamically change the project and dataset. For example

Instead of

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

I want

project = my_project
dataset = my_dataset

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

1

There are 1 best solutions below

0
Enrique Zetina On BEST ANSWER

According to the IPython Magics for BigQuery documentation is not possible to pass the project nor the dataset as parameters; nonetheless, you can use the BigQuery client library to perform this action in 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"]))

I also recommend you to take a look in public documentation to know how to visualize BigQuery data in a Jupyter notebooks.