Using BigQuery in Python

CK CK 3788 
Created at  
408 0 0

To access Google BigQuery in Python, you typically use the google-cloud-bigquery library, which is part of the Google Cloud Client Library for Python. Here are the steps to get started:

  1. Install the Google Cloud BigQuery Library

    First, you need to install the google-cloud-bigquery package. You can do this using pip:

    pip install google-cloud-bigquery
  2. Set Up Authentication

    You need to set up authentication to access your BigQuery datasets. The recommended way is to use a service account key file. Here's how you can do it:

    1. Go to the Google Cloud Console.
    2. Create a project if you don't have one already.
    3. Enable the BigQuery API for your project.
    4. Create a service account in your project and download the JSON key file.

    Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of your service account key file:

    export GOOGLE_APPLICATION_CREDENTIALS="path/to/your-service-account-key.json"
    
  3. Write Python Code to Query BigQuery

    Here is an example of how to use the google-cloud-bigquery library to query data from BigQuery:

    from google.cloud import bigquery
    
    # Initialize a BigQuery client
    client = bigquery.Client()
    
    # Define your query
    query = """
    SELECT
      name,
      SUM(number) as total_number
    FROM
      `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE
      state = 'TX'
    GROUP BY
      name
    ORDER BY
      total_number DESC
    LIMIT 10
    """
    
    # Execute the query
    query_job = client.query(query)
    
    # Get the results
    results = query_job.result()
    
    # Process the results
    for row in results:
        print(f"{row.name}: {row.total_number}")
    

This script initializes a BigQuery client, runs a query to get the top 10 names by number in Texas, and prints the results.

Additional Tips

  • Using Pandas: If you prefer to work with data in pandas DataFrames, you can use the bigquery.Client with pandas:

    import pandas as pd
    from google.cloud import bigquery
    
    # Initialize a BigQuery client
    client = bigquery.Client()
    
    # Define your query
    query = """
    SELECT
      name,
      SUM(number) as total_number
    FROM
      `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE
      state = 'TX'
    GROUP BY
      name
    ORDER BY
      total_number DESC
    LIMIT 10
    """
    
    # Execute the query and convert the results to a DataFrame
    df = client.query(query).to_dataframe()
    
    # Display the DataFrame
    print(df)
    
  • Handling Large Queries: For large queries, you might want to write the results to a table instead of fetching them directly.

    from google.cloud import bigquery
    
    client = bigquery.Client()
    
    job_config = bigquery.QueryJobConfig(
        destination="your_project.your_dataset.your_table",
        write_disposition="WRITE_TRUNCATE",
    )
    
    query = """
    SELECT ...
    """
    
    query_job = client.query(query, job_config=job_config)
    
    query_job.result()  # Wait for the job to complete.
    

These steps should help you get started with accessing Google BigQuery from Python.

Tags GOOGLE_APPLICATION_CREDENTIALS bigquery google-cloud-bigquery Facebook X
Comments 0
Similar posts
  1. Simple Example to get the total number of records in BigQuery with Python
    665
  2. Google BigQuery Example to converted Nested FIelds in JSON
    458
  3. Node.js code example to access Google BigQuery
    1,179
  1. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    902
  2. Deleting a specific user voice from the original audio track with Python
    547
  3. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    436
  4. Creating mp3 audio file based on the text input with Python
    464
  5. Implementing Text To Speech / Audio with Python3 and pyttsx3
    354
  6. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  7. Python Simplified Assignment Operators
    533
  8. Trackback module used for Python Threading debugging
    840
  9. Python Flask with simple HTML files to server web pages along with API
    926
  10. Python Flask web server tutorial from the scratch
    618
  11. Simple Web Server based in Python
    368
  12. Thread Implementation in Python
    508
  13. A shell script that activates a Python virtual environment and then runs a specific Python script
    741
  14. Learning about Python Multiprocessing Technique
    591
  15. Simple Example to get the total number of records in BigQuery with Python
    665
  16. Python Web Programming based on Django from the Scratch
    366
  17. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    184
  18. How do I determine the client IP type in Python - IPv4 or IPv6
    760
  19. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,231
  20. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  21. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  22. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  23. Milvus & FAISS: Decoding Their ML Synergy
    276
  24. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    376
  25. Forecasting with Linear Regression and KNN Regression in Python
    920
  26. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,431
  27. Uvicorn, Gunicorn: Proving Your Production Prowess
    395
  28. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  29. Harnessing the Power of Random Forest Algorithm in Python
    657
  30. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    632
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,728
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252