BigQuery を使用するシンプルなアプリを作成します。
このコードサンプルが含まれるドキュメント ページ
コンテキストで使用されているコードサンプルを見るには、次のドキュメントをご覧ください。
コードサンプル
C#
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、BigQuery C# API のリファレンス ドキュメントをご覧ください。
using System;
using Google.Cloud.BigQuery.V2;
namespace GoogleCloudSamples
{
public class Program
{
public static void Main(string[] args)
{
string projectId = "YOUR-PROJECT-ID";
var client = BigQueryClient.Create(projectId);
string query = @"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";
var result = client.ExecuteQuery(query, parameters: null);
Console.Write("\nQuery Results:\n------------\n");
foreach (var row in result)
{
Console.WriteLine($"{row["url"]}: {row["view_count"]} views");
}
}
}
}
Go
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用の Go の手順に従って設定を行ってください。詳細については、BigQuery Go API のリファレンス ドキュメントをご覧ください。
import (
"context"
"fmt"
"io"
"log"
"os"
"cloud.google.com/go/bigquery"
"google.golang.org/api/iterator"
)
func main() {
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
fmt.Println("GOOGLE_CLOUD_PROJECT environment variable must be set.")
os.Exit(1)
}
ctx := context.Background()
client, err := bigquery.NewClient(ctx, projectID)
if err != nil {
log.Fatalf("bigquery.NewClient: %v", err)
}
defer client.Close()
rows, err := query(ctx, client)
if err != nil {
log.Fatal(err)
}
if err := printResults(os.Stdout, rows); err != nil {
log.Fatal(err)
}
}
// query returns a row iterator suitable for reading query results.
func query(ctx context.Context, client *bigquery.Client) (*bigquery.RowIterator, error) {
query := client.Query(
`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;`)
return query.Read(ctx)
}
type StackOverflowRow struct {
URL string `bigquery:"url"`
ViewCount int64 `bigquery:"view_count"`
}
// printResults prints results from a query to the Stack Overflow public dataset.
func printResults(w io.Writer, iter *bigquery.RowIterator) error {
for {
var row StackOverflowRow
err := iter.Next(&row)
if err == iterator.Done {
return nil
}
if err != nil {
return fmt.Errorf("error iterating through results: %v", err)
}
fmt.Fprintf(w, "url: %s views: %d\n", row.URL, row.ViewCount)
}
}
Java
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、BigQuery Java API のリファレンス ドキュメントをご覧ください。
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 commit, author, repo_name "
+ "FROM `bigquery-public-data.github_repos.commits` "
+ "WHERE subject like '%bigquery%' "
+ "ORDER BY subject 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 commit = row.get("commit").getStringValue();
// Record type
FieldValueList author = row.get("author").getRecordValue();
String name = author.get("name").getStringValue();
String email = author.get("email").getStringValue();
// String Repeated type
String repoName = row.get("repo_name").getRecordValue().get(0).getStringValue();
System.out.printf(
"Repo name: %s Author name: %s email: %s commit: %s\n", repoName, name, email, commit);
}
}
}
Node.js
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、BigQuery Node.js API のリファレンス ドキュメントをご覧ください。
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
async function queryStackOverflow() {
// Queries a public Stack Overflow dataset.
// Create a client
const bigqueryClient = new BigQuery();
// The SQL query to run
const sqlQuery = `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`;
const options = {
query: sqlQuery,
// Location must match that of the dataset(s) referenced in the query.
location: 'US',
};
// Run the query
const [rows] = await bigqueryClient.query(options);
console.log('Query Results:');
rows.forEach(row => {
const url = row['url'];
const viewCount = row['view_count'];
console.log(`url: ${url}, ${viewCount} views`);
});
}
queryStackOverflow();
PHP
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用にある PHP 向けの手順に従って設定を行ってください。詳細については、BigQuery PHP API のリファレンス ドキュメントをご覧ください。
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\BigQuery\BigQueryClient;
// get the project ID as the first argument
if (2 != count($argv)) {
die("Usage: php stackoverflow.php YOUR_PROJECT_ID\n");
}
$projectId = $argv[1];
$bigQuery = new BigQueryClient([
'projectId' => $projectId,
]);
$query = <<<ENDSQL
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;
ENDSQL;
$queryJobConfig = $bigQuery->query($query);
$queryResults = $bigQuery->runQuery($queryJobConfig);
if ($queryResults->isComplete()) {
$i = 0;
$rows = $queryResults->rows();
foreach ($rows as $row) {
printf('--- Row %s ---' . PHP_EOL, ++$i);
printf('url: %s, %s views' . PHP_EOL, $row['url'], $row['view_count']);
}
printf('Found %s row(s)' . PHP_EOL, $i);
} else {
throw new Exception('The query failed to complete');
}
Python
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用の Python の手順に従って設定を行ってください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。
from google.cloud import bigquery
def query_stackoverflow():
client = bigquery.Client()
query_job = client.query(
"""
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"""
)
results = query_job.result() # Waits for job to complete.
for row in results:
print("{} : {} views".format(row.url, row.view_count))
if __name__ == "__main__":
query_stackoverflow()
Ruby
このサンプルを試す前に、BigQuery クイックスタート: クライアント ライブラリの使用で説明している Ruby 向けの手順に沿って設定を行ってください。詳細については、BigQuery Ruby API のリファレンス ドキュメントをご覧ください。
require "google/cloud/bigquery"
# This uses Application Default Credentials to authenticate.
# @see https://cloud.google.com/bigquery/docs/authentication/getting-started
bigquery = Google::Cloud::Bigquery.new
sql = "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"
results = bigquery.query sql
results.each do |row|
puts "#{row[:url]}: #{row[:view_count]} views"
end
次のステップ
他の Google Cloud プロダクトに関連するコードサンプルの検索および条件付き検索を行うには、Google Cloud のサンプル ブラウザをご覧ください。