BigQuery API 用戶端程式庫

本頁面說明如何開始使用 BigQuery API 適用的 Cloud 用戶端程式庫。用戶端程式庫可讓您更輕鬆地透過支援的語言存取Google Cloud API。雖然您可以直接向伺服器發出原始要求來使用Google Cloud API,但用戶端程式庫提供簡化功能,可大幅減少您需要編寫的程式碼數量。

如要進一步瞭解 Cloud 用戶端程式庫和舊版 Google API 用戶端程式庫,請參閱用戶端程式庫說明

安裝用戶端程式庫

C#

Install-Package Google.Cloud.BigQuery.V2 -Pre

詳情請參閱「設定 C# 開發環境」。

Go

go get cloud.google.com/go/bigquery

詳情請參閱「設定 Go 開發環境」一文。

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<!--  Using libraries-bom to manage versions.
See https://github.com/GoogleCloudPlatform/cloud-opensource-java/wiki/The-Google-Cloud-Platform-Libraries-BOM -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.62.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-bigquery</artifactId>
  </dependency>
</dependencies>

If you are using Gradle, add the following to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.45.0')

implementation 'com.google.cloud:google-cloud-bigquery'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-bigquery" % "2.42.2"

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

詳情請參閱「設定 Java 開發環境」一文。

Node.js

npm install @google-cloud/bigquery

詳情請參閱「設定 Node.js 開發環境」一文。

PHP

composer require google/cloud-bigquery

詳情請參閱「在 Google Cloud 上使用 PHP」。

Python

pip install --upgrade google-cloud-bigquery

詳情請參閱「設定 Python 開發環境」一文。

Ruby

gem install google-cloud-bigquery

詳情請參閱「設定 Ruby 開發環境」一文。

設定驗證方法

為了驗證對 Google Cloud API 的呼叫,用戶端程式庫支援應用程式預設憑證 (ADC);這些程式庫會在一系列定義的位置尋找憑證,然後使用這些憑證驗證對 API 的要求。有了 ADC,您就能在各種環境 (例如本機開發或正式版) 中為應用程式提供憑證,而無需修改應用程式程式碼。

在實際工作環境中,您設定 ADC 的方式取決於服務和情境。詳情請參閱「設定應用程式預設憑證」。

如果是本機開發環境,您可以使用與 Google 帳戶相關聯的憑證設定 ADC:

  1. After installing the Google Cloud CLI, initialize it by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    系統隨即會顯示登入畫面。登入後,憑證會儲存在 ADC 使用的本機憑證檔案中。

使用用戶端程式庫

以下範例說明如何初始化用戶端,並對 BigQuery API 公開資料集執行查詢。

C#


using Google.Cloud.BigQuery.V2;
using System;

public class BigQueryQuery
{
    public void Query(
        string projectId = "your-project-id"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        string query = @"
            SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013`
            WHERE state = 'TX'
            LIMIT 100";
        BigQueryJob job = client.CreateQueryJob(
            sql: query,
            parameters: null,
            options: new QueryOptions { UseQueryCache = false });
        // Wait for the job to complete.
        job = job.PollUntilCompleted().ThrowOnAnyError();
        // Display the results
        foreach (BigQueryRow row in client.GetQueryResults(job.Reference))
        {
            Console.WriteLine($"{row["name"]}");
        }
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
	"google.golang.org/api/iterator"
)

// queryBasic demonstrates issuing a query and reading results.
func queryBasic(w io.Writer, projectID string) error {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	q := client.Query(
		"SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` " +
			"WHERE state = \"TX\" " +
			"LIMIT 100")
	// Location must match that of the dataset(s) referenced in the query.
	q.Location = "US"
	// Run the query and print results when the query job is completed.
	job, err := q.Run(ctx)
	if err != nil {
		return err
	}
	status, err := job.Wait(ctx)
	if err != nil {
		return err
	}
	if err := status.Err(); err != nil {
		return err
	}
	it, err := job.Read(ctx)
	for {
		var row []bigquery.Value
		err := it.Next(&row)
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintln(w, row)
	}
	return nil
}

Java


import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobId;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.TableResult;


public class SimpleApp {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the app.
    String projectId = "MY_PROJECT_ID";
    simpleApp(projectId);
  }

  public static void simpleApp(String projectId) {
    try {
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
      QueryJobConfiguration queryConfig =
          QueryJobConfiguration.newBuilder(
                  "SELECT CONCAT('https://stackoverflow.com/questions/', "
                      + "CAST(id as STRING)) as url, view_count "
                      + "FROM `bigquery-public-data.stackoverflow.posts_questions` "
                      + "WHERE tags like '%google-bigquery%' "
                      + "ORDER BY view_count DESC "
                      + "LIMIT 10")
              // Use standard SQL syntax for queries.
              // See: https://cloud.google.com/bigquery/sql-reference/
              .setUseLegacySql(false)
              .build();

      JobId jobId = JobId.newBuilder().setProject(projectId).build();
      Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

      // Wait for the query to complete.
      queryJob = queryJob.waitFor();

      // Check for errors
      if (queryJob == null) {
        throw new RuntimeException("Job no longer exists");
      } else if (queryJob.getStatus().getExecutionErrors() != null
          && queryJob.getStatus().getExecutionErrors().size() > 0) {
        // TODO(developer): Handle errors here. An error here do not necessarily mean that the job
        // has completed or was unsuccessful.
        // For more details: https://cloud.google.com/bigquery/troubleshooting-errors
        throw new RuntimeException("An unhandled error has occurred");
      }

      // Get the results.
      TableResult result = queryJob.getQueryResults();

      // Print all pages of the results.
      for (FieldValueList row : result.iterateAll()) {
        // String type
        String url = row.get("url").getStringValue();
        String viewCount = row.get("view_count").getStringValue();
        System.out.printf("%s : %s views\n", url, viewCount);
      }
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Simple App failed due to error: \n" + e.toString());
    }
  }
}

Node.js

// Import the Google Cloud client library using default credentials
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();
async function query() {
  // Queries the U.S. given names dataset for the state of Texas.

  const query = `SELECT name
    FROM \`bigquery-public-data.usa_names.usa_1910_2013\`
    WHERE state = 'TX'
    LIMIT 100`;

  // For all options, see https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query
  const options = {
    query: query,
    // Location must match that of the dataset(s) referenced in the query.
    location: 'US',
  };

  // Run the query as a job
  const [job] = await bigquery.createQueryJob(options);
  console.log(`Job ${job.id} started.`);

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

  // Print the results
  console.log('Rows:');
  rows.forEach(row => console.log(row));
}

PHP

use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\Core\ExponentialBackoff;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $query = 'SELECT id, view_count FROM `bigquery-public-data.stackoverflow.posts_questions`';

$bigQuery = new BigQueryClient([
    'projectId' => $projectId,
]);
$jobConfig = $bigQuery->query($query);
$job = $bigQuery->startQuery($jobConfig);

$backoff = new ExponentialBackoff(10);
$backoff->execute(function () use ($job) {
    print('Waiting for job to complete' . PHP_EOL);
    $job->reload();
    if (!$job->isComplete()) {
        throw new Exception('Job has not yet completed', 500);
    }
});
$queryResults = $job->queryResults();

$i = 0;
foreach ($queryResults as $row) {
    printf('--- Row %s ---' . PHP_EOL, ++$i);
    foreach ($row as $column => $value) {
        printf('%s: %s' . PHP_EOL, $column, json_encode($value));
    }
}
printf('Found %s row(s)' . PHP_EOL, $i);

Python

from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client()

query = """
    SELECT name, SUM(number) as total_people
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE state = 'TX'
    GROUP BY name, state
    ORDER BY total_people DESC
    LIMIT 20
"""
rows = client.query_and_wait(query)  # Make an API request.

print("The query data:")
for row in rows:
    # Row values can be accessed by field name or index.
    print("name={}, count={}".format(row[0], row["total_people"]))

Ruby

require "google/cloud/bigquery"

def query
  bigquery = Google::Cloud::Bigquery.new
  sql = "SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` " \
        "WHERE state = 'TX' " \
        "LIMIT 100"

  # Location must match that of the dataset(s) referenced in the query.
  results = bigquery.query sql do |config|
    config.location = "US"
  end

  results.each do |row|
    puts row.inspect
  end
end

其他資源

C#

以下清單包含與 C# 用戶端程式庫相關的更多資源連結:

Go

以下清單包含與 Go 用戶端程式庫相關的更多資源連結:

Java

下列清單包含適用於 Java 用戶端程式庫的更多資源連結:

Node.js

以下清單列出與 Node.js 用戶端程式庫相關的更多資源連結:

PHP

下列清單包含與 PHP 用戶端程式庫相關的更多資源連結:

Python

以下清單包含與 Python 用戶端程式庫相關的更多資源連結:

Ruby

以下清單包含與 Ruby 用戶端程式庫相關的更多資源連結:

第三方 BigQuery API 用戶端程式庫

除了上表列出的 Google 支援的用戶端程式庫外,還可使用一組第三方程式庫。

語言 程式庫
Python pandas-gbq (使用指南)、ibis (教學課程)
R bigrqueryBigQueryR
Scala spark-bigquery-connector

後續步驟

歡迎試用

如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用 BigQuery 的成效。新客戶可以獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。

免費試用 BigQuery