Node.js code example to access Google BigQuery

CK CK 3788 
Created at
Updated at  
1,184 0 0

To access Google BigQuery from a Node.js application, you can use the @google-cloud/bigquery client library provided by Google. This library simplifies interactions with BigQuery, allowing you to execute queries, load data, and manage datasets.

Here's a step-by-step example of how to set up and use the @google-cloud/bigquery library in a Node.js application:

 

Step 1: Install the BigQuery Client Library

First, you need to install the @google-cloud/bigquery library:

npm install @google-cloud/bigquery

 

Step 2: Set Up Authentication

To authenticate your application, you need to set up a Google Cloud service account with the appropriate BigQuery permissions.

  1. Create a Service Account: Go to the Google Cloud Console, navigate to IAM & Admin > Service Accounts, and create a new service account. Grant it the BigQuery Admin role or other appropriate roles based on your needs.
  2. Generate and Download the Key: Create and download a JSON key file for the service account.
  3. Set the GOOGLE_APPLICATION_CREDENTIALS Environment Variable: This variable should point to the path of your service account key file. You can set it in your environment or in your Node.js application.

    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-service-account-key.json"
    

 

Step 3: Write Node.js Code to Access BigQuery

Here's an example of a Node.js script that queries BigQuery and retrieves data:

File: bigquery-example.js

const { BigQuery } = require('@google-cloud/bigquery');

// Create a BigQuery client
const bigquery = new BigQuery();

// Define your SQL query
const query = `
  SELECT
    name,
    COUNT(*) as count
  FROM
    \`my-project.my_dataset.my_table\`
  GROUP BY
    name
  ORDER BY
    count DESC
  LIMIT 10
`;

async function queryBigQuery() {
  try {
    // Run the query
    const [job] = await bigquery.createQueryJob({
      query: query,
      location: 'US', // Replace with your dataset's location
    });

    console.log(`Job ${job.id} started.`);

    // Wait for the query to complete
    const [rows] = await job.getQueryResults();

    // Print the results
    console.log('Query Results:');
    rows.forEach(row => console.log(row));
  } catch (error) {
    console.error('Error running query:', error);
  }
}

// Execute the function
queryBigQuery();

Explanation

  1. Create BigQuery Client: Initialize the BigQuery client using the BigQuery class from the @google-cloud/bigquery package.
  2. Define SQL Query: Set the SQL query you want to run against your BigQuery dataset.
  3. Run the Query: Use createQueryJob to start a query job. The location parameter should match the location of your BigQuery dataset.
  4. Get Query Results: Use getQueryResults to wait for the query to complete and retrieve the results.
  5. Handle Errors: Catch and log any errors that occur during the query execution.

 

Run the Script

Execute the script using Node.js:

node bigquery-example.js

This script will connect to BigQuery, execute the query, and print the results.

Additional Features

The @google-cloud/bigquery library supports many other features, including:

  • Loading data from files into BigQuery.
  • Managing datasets and tables.
  • Streaming data into BigQuery.

 

If you don't want to use the environmental variable, you can directly attach its key when you create the bigquery instance:

const { BigQuery } = require('@google-cloud/bigquery');
const path = require('path');
const fs = require('fs');

// Path to your service account key file
const keyFilename = path.join(__dirname, 'path/to/your-service-account-key.json');

// Create a BigQuery client with explicit credentials
const bigquery = new BigQuery({ keyFilename });

const query = `
  SELECT
    name,
    COUNT(*) as count
  FROM
    \`my-project.my_dataset.my_table\`
  GROUP BY
    name
  ORDER BY
    count DESC
  LIMIT 10
`;

async function queryBigQuery() {
  try {
    // Run the query
    const [job] = await bigquery.createQueryJob({
      query: query,
      location: 'US', // Replace with your dataset's location
    });

    console.log(`Job ${job.id} started.`);

    // Wait for the query to complete
    const [rows] = await job.getQueryResults();

    // Print the results
    console.log('Query Results:');
    rows.forEach(row => console.log(row));
  } catch (error) {
    console.error('Error running query:', error);
  }
}

// Execute the function
queryBigQuery();

 

Refer to the official documentation for more details on using the BigQuery client library.

Tags BigQuery Client Library GOOGLE_APPLICATION_CREDENTIALS Google BigQuery Node.js BigQuery Node.js Google BigQuery Facebook X
Comments 0
Similar posts
  1. Using BigQuery in Python
    414
  2. Google BigQuery Example to converted Nested FIelds in JSON
    461
  1. Get client IP address and user agent in Node.js
    1,531
  2. forEach method in JavaScript when working with arrays
    667
  3. CRC32B function code in Javascript
    1,846
  4. Node.js-based Web Server supporting multiple path
    604
  5. A simple Javascript class example with static method for Node.js
    662
  6. Setting a Common Path for require() in Node.js
    1,007
  7. Import all JS files in a specific folder for Node.js programming
    1,733
  8. A simple example to access a PostgreSQL database in Node.js
    1,101
  9. Investigation on package.js for Node.js source code
    824
  10. Using MySQL in Node.js
    485
  11. A Node.js script that checks if a module is installed before requiring it
    774
  12. Worker Threads and Mutual Exclusion in Node.js
    466
  13. Using a module in the external class itself without creating an instance in Node.js
    350
  14. Node.js external modules
    434
  15. Multi-threaded Web Server based in Node.js
    867
  16. A basic HTTP server based in Node.js
    544
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,256
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    105
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    108
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    209
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    154
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    117
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    599
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    355
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    231
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    229
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    204
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233