テンプレートを使用してテーブルを作成する

1 つのテーブルのプロパティ(スキーマ、パーティショニング、クラスタリング)を使用してテーブルを作成し、同じ構成で新しい空のテーブルを作成します。

コードサンプル

Go

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートGo の手順に沿って設定を行ってください。詳細については、BigQuery Go API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"

	"cloud.google.com/go/bigquery"
)

// createTableFromTemplateTable demonstrates how to use the properties of one
// table (schema, partitioning, clustering) to create a new empty table with
// the same configuration.
func createTableFromTemplateTable(srcProjectID, srcDatasetID, srcTableID, dstProjectID, dstDatasetID, dstTableID string) error {
	// srcProjectID := "bigquery-public-data"
	// srcDatasetID := "samples"
	// srcTableID := "shakespeare"
	// dstProjectID := "my-project-id"
	// dstDatasetID := "mydataset"
	// dstTableID := "mytable"
	ctx := context.Background()

	// We'll construct the client based on the destination project.
	client, err := bigquery.NewClient(ctx, dstProjectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	srcTableRef := client.DatasetInProject(srcProjectID, srcDatasetID).Table(srcTableID)

	srcMeta, err := srcTableRef.Metadata(ctx)
	if err != nil {
		return fmt.Errorf("failed to get source table metadata: %w", err)
	}

	dstTableRef := client.Dataset(dstDatasetID).Table(dstTableID)

	// We'll use some (but not all) of the metadata from the source table
	// to define the destination table.  Other properties to consider include
	// attributes like expiration policy and managed encryption settings.
	dstMeta := &bigquery.TableMetadata{
		Description: fmt.Sprintf("table structure copied from %s.%s.%s",
			srcTableRef.ProjectID, srcTableRef.DatasetID, srcTableRef.TableID),
		Schema:     srcMeta.Schema,
		Clustering: srcMeta.Clustering,
		// A table will only have one partitioning configuration, the others will be empty/nil.
		TimePartitioning:  srcMeta.TimePartitioning,
		RangePartitioning: srcMeta.RangePartitioning,
		// Retain the same enforcement of partition filtering as well.
		RequirePartitionFilter: srcMeta.RequirePartitionFilter,
	}

	if err := dstTableRef.Create(ctx, dstMeta); err != nil {
		return err
	}

	return nil
}

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。