BigQuery API クライアント ライブラリ

このページでは、BigQuery API の Cloud クライアント ライブラリの使用を開始する方法を説明します。クライアント ライブラリを使用すると、サポートされている言語で Google Cloud APIs に簡単にアクセスできます。サーバーにリクエストを送信して Google Cloud APIs を直接利用することもできますが、クライアント ライブラリを使用すると、記述するコードの量を大幅に削減できます。

Cloud クライアント ライブラリと以前の Google API クライアント ライブラリの詳細については、クライアント ライブラリの説明をご覧ください。

クライアント ライブラリをインストールする

C#

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

詳細については、C# 開発環境の設定をご覧ください。

Go

go get cloud.google.com/go/bigquery

詳細については、Go 開発環境の設定をご覧ください。

Java

Maven を使用している場合は、以下を pom.xml ファイルに追加します。BOM の詳細については、Google Cloud Platform ライブラリ 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.20.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>

Gradle を使用している場合は、以下を依存関係に追加します。

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

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

sbt を使用している場合は、以下を依存関係に追加します。

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

Visual Studio Code、IntelliJ または Eclipse を使用している場合は、次の IDE プラグインでプロジェクトにクライアント ライブラリを追加できます。

プラグインでは、サービス アカウントのキー管理などの追加機能も提供されます。詳細は各プラグインのドキュメントをご覧ください。

詳細については、Java 開発環境の設定をご覧ください。

Node.js

npm install --save @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 APIs の呼び出しを認証するために、クライアント ライブラリではアプリケーションのデフォルト認証情報(ADC)がサポートされています。このライブラリは、一連の定義済みのロケーションの中から認証情報を探し、その認証情報を使用して API へのリクエストを認証します。ADC を使用すると、アプリケーション コードを変更することなく、ローカルでの開発や本番環境など、さまざまな環境のアプリケーションで認証情報を使用できるようになります。

本番環境では、ADC の設定方法はサービスとコンテキストによって異なります。詳細については、アプリケーションのデフォルト認証情報を設定するをご覧ください。

ローカル開発環境では、Google アカウントに関連付けられている認証情報を使用して ADC を設定できます。

  1. gcloud CLI をインストールして初期化します

    gcloud CLI を初期化するときは、アプリケーションに必要なリソースにアクセスする権限がある Google Cloud プロジェクトを指定してください。

  2. 認証情報ファイルを作成します。

    gcloud auth application-default login

    ログイン画面が表示されます。ログインすると、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.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;
import java.util.UUID;

public class SimpleApp {
  public static void main(String... args) throws Exception {
    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();

    // Create a job ID so that we can safely retry.
    JobId jobId = JobId.of(UUID.randomUUID().toString());
    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().getError() != null) {
      // You can also look at queryJob.getStatus().getExecutionErrors() for all
      // errors, not just the latest one.
      throw new RuntimeException(queryJob.getStatus().getError().toString());
    }

    // 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);
    }
  }
}

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 の無料トライアル