ספריות לקוח ל-BigQuery API

בדף הזה מוסבר איך מתחילים להשתמש בספריות הלקוח של Cloud עבור BigQuery API. ספריות לקוח מאפשרות לגשת בקלות ל-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

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 or IntelliJ, 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

מידע נוסף זמין במאמר שימוש ב-PHP ב-Google Cloud.

Python

pip install --upgrade google-cloud-bigquery

מידע נוסף מופיע במאמר הגדרת סביבת פיתוח בשפת Python.

Ruby

gem install google-cloud-bigquery

מידע נוסף זמין במאמר הגדרת סביבת פיתוח בשפת Ruby.

מגדירים אימות

כדי לאמת קריאות לממשקי ה-API של Google Cloud , ספריות הלקוח תומכות ב-Application Default Credentials ‏ (ADC). בספריות מתבצע חיפוש של פרטי כניסה בקבוצה של מיקומים מוגדרים, והמערכת משתמשת בפרטי הכניסה האלה כדי לאמת בקשות ל-API. בעזרת ADC, פרטי הכניסה לאפליקציה יכולים להיות זמינים בסביבות שונות, כמו בפיתוח מקומי או בייצור, בלי שיהיה צריך לשנות את קוד האפליקציה.

בסביבות ייצור, אופן ההגדרה של ADC תלוי בשירות ובהקשר. מידע נוסף זמין במאמר בנושא הגדרה של Application Default Credentials.

בסביבת פיתוח מקומית, אפשר להגדיר את ADC עם פרטי הכניסה שמשויכים לחשבון Google שלכם:

  1. Install the Google Cloud CLI. After installation, initialize the Google Cloud CLI 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 DataFrames‏ (BigFrames)

BigQuery DataFrames הוא ממשק API של Pythonic DataFrame ולמידת מכונה (ML) שמבוסס על מנוע BigQuery. הוא מטמיע את ממשקי ה-API של pandas ו-scikit-learn על ידי העברת העיבוד ל-BigQuery באמצעות המרה ל-SQL.

כדי להתחיל לעבוד עם BigQuery DataFrames, צריך להתקין את הספרייה:

pip install --upgrade bigframes

בדוגמה הבאה מוצג איך לאתחל BigQuery DataFrames ולהריץ שאילתה פשוטה.

import bigframes.pandas as bpd

# Set BigQuery DataFrames options
# Note: The project option is not required in all environments.
# On BigQuery Studio, the project ID is automatically detected.
bpd.options.bigquery.project = your_gcp_project_id

# Use "partial" ordering mode to generate more efficient queries, but the
# order of the rows in DataFrames may not be deterministic if you have not
# explictly sorted it. Some operations that depend on the order, such as
# head() will not function until you explictly order the DataFrame. Set the
# ordering mode to "strict" (default) for more pandas compatibility.
bpd.options.bigquery.ordering_mode = "partial"

# Create a DataFrame from a BigQuery table
query_or_table = "bigquery-public-data.ml_datasets.penguins"
df = bpd.read_gbq(query_or_table)

# Efficiently preview the results using the .peek() method.
df.peek()

מידע נוסף זמין במסמכי העיון בנושא BigQuery DataFrames ובמאמר תחילת העבודה עם BigQuery DataFrames.

ספריות לקוח של צד שלישי ל-BigQuery API

בנוסף לספריות הלקוח שנתמכות על ידי Google ומפורטות בטבלאות שלמעלה, יש גם קבוצה של ספריות צד שלישי.

שפה ספרייה
Python pandas-gbq (מדריך לשימוש), ‏ ibis (הדרכה)
R bigrquery, ‏ BigQueryR
Scala spark-bigquery-connector

מה השלב הבא?

נסו בעצמכם

אנחנו ממליצים למשתמשים חדשים ב-Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של BigQuery בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300 $להרצה, לבדיקה ולפריסה של עומסי העבודה.

מתנסים ב-BigQuery בחינם