테이블 관리

이 문서에서는 BigQuery에서 테이블을 관리하는 방법을 설명합니다. 다음 방법으로 BigQuery 테이블을 관리할 수 있습니다.

  • 테이블 속성을 업데이트합니다.
    • 만료 시간
    • 설명
    • 스키마 정의
    • 라벨
  • 테이블 이름 바꾸기(복사)
  • 테이블 복사
  • 테이블 삭제
  • 삭제된 테이블 복원

테이블 정보 가져오기, 테이블 나열, 테이블 데이터 액세스 제어를 비롯하여 테이블 만들기 및 사용에 대한 자세한 내용은 테이블 만들기 및 사용을 참조하세요.

시작하기 전에

사용자에게 이 문서의 각 작업을 수행하는 데 필요한 권한을 부여하는 Identity and Access Management(IAM) 역할을 부여합니다. 태스크를 수행하는 데 필요한 권한(있는 경우)이 태스크의 '필요한 권한' 섹션에 나열됩니다.

테이블 속성 업데이트

테이블의 다음 요소를 업데이트할 수 있습니다.

필수 권한

테이블을 업데이트하려면 다음 IAM 권한이 필요합니다.

  • bigquery.tables.update
  • bigquery.tables.get

다음과 같은 사전 정의된 IAM 역할에는 테이블을 업데이트하는 데 필요한 권한이 포함되어 있습니다.

  • roles/bigquery.dataEditor
  • roles/bigquery.dataOwner
  • roles/bigquery.admin

또한 bigquery.datasets.create 권한이 있으면 만드는 데이터 세트의 테이블 속성을 업데이트할 수 있습니다.

BigQuery의 IAM 역할과 권한에 대한 자세한 내용은 사전 정의된 역할 및 권한을 참조하세요.

테이블 설명 업데이트

다음 방법으로 테이블 설명을 업데이트할 수 있습니다.

  • 콘솔 사용
  • 데이터 정의 언어(DDL) ALTER TABLE 문 사용
  • bq 명령줄 도구의 bq update 명령어 사용
  • tables.patch API 메서드 호출
  • 클라이언트 라이브러리 사용

테이블 설명을 업데이트하는 방법:

콘솔

콘솔을 사용하여 테이블을 만들 때에는 설명을 추가할 수 없습니다. 테이블이 생성된 후 세부정보 페이지에서 설명을 추가할 수 있습니다.

  1. 탐색기 패널에서 프로젝트와 데이터 세트를 펼친 후 테이블을 선택합니다.

  2. 세부정보 패널에서 세부정보를 클릭합니다.

  3. 설명 섹션에서 연필 아이콘을 클릭하여 설명을 수정합니다.

    설명 수정

  4. 상자에 설명을 입력하고 업데이트를 클릭하여 저장합니다.

SQL

ALTER TABLE SET OPTIONS을 사용합니다. 다음 예시에서는 mytable이라는 테이블의 설명을 업데이트합니다.

  1. 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력합니다.

    ALTER TABLE mydataset.mytable
      SET OPTIONS (
        description = 'Description of mytable');
    

  3. 실행을 클릭합니다.

쿼리를 실행하는 방법에 대한 자세한 내용은 대화형 쿼리 실행을 참조하세요.

bq

bq update 명령어를 --description 플래그와 함께 실행합니다. 기본 프로젝트가 아닌 다른 프로젝트의 테이블을 업데이트하려면 프로젝트 ID를 project_id:dataset 형식으로 데이터 세트 이름에 추가합니다.

bq update \
--description "description" \
project_id:dataset.table

다음을 바꿉니다.

  • description: 따옴표로 묶은 테이블을 설명하는 텍스트
  • project_id: 프로젝트 ID입니다.
  • dataset: 업데이트할 테이블이 포함된 데이터 세트의 이름
  • table: 업데이트할 테이블의 이름

예를 들면 다음과 같습니다.

mydataset 데이터 세트의 mytable 테이블 설명을 'Description of mytable'로 변경하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트에 있습니다.

bq update --description "Description of mytable" mydataset.mytable

mydataset 데이터 세트의 mytable 테이블 설명을 'Description of mytable'로 변경하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트가 아닌 myotherproject 프로젝트에 있습니다.

bq update \
--description "Description of mytable" \
myotherproject:mydataset.mytable

API

tables.patch 메서드를 호출하고 테이블 리소스description 속성을 사용하여 테이블 설명을 업데이트합니다. tables.update 메서드는 전체 테이블 리소스를 바꾸기 때문에 tables.patch 메서드를 사용하는 것이 좋습니다.

Go

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 BigQuery Go API 참조 문서를 확인하세요.

import (
	"context"
	"fmt"

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

// updateTableDescription demonstrates how to fetch a table's metadata and updates the Description metadata.
func updateTableDescription(projectID, datasetID, tableID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// tableID := "mytable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	tableRef := client.Dataset(datasetID).Table(tableID)
	meta, err := tableRef.Metadata(ctx)
	if err != nil {
		return err
	}
	update := bigquery.TableMetadataToUpdate{
		Description: "Updated description.",
	}
	if _, err = tableRef.Update(ctx, update, meta.ETag); err != nil {
		return err
	}
	return nil
}

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Table;

public class UpdateTableDescription {

  public static void runUpdateTableDescription() {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    String newDescription = "this is the new table description";
    updateTableDescription(datasetName, tableName, newDescription);
  }

  public static void updateTableDescription(
      String datasetName, String tableName, String newDescription) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      Table table = bigquery.getTable(datasetName, tableName);
      bigquery.update(table.toBuilder().setDescription(newDescription).build());
      System.out.println("Table description updated successfully to " + newDescription);
    } catch (BigQueryException e) {
      System.out.println("Table description was not updated \n" + e.toString());
    }
  }
}

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.

Table.description 속성을 구성하고 Client.update_table()을 호출하여 업데이트를 API에 보냅니다.
# from google.cloud import bigquery
# client = bigquery.Client()
# project = client.project
# dataset_ref = bigquery.DatasetReference(project, dataset_id)
# table_ref = dataset_ref.table('my_table')
# table = client.get_table(table_ref)  # API request

assert table.description == "Original description."
table.description = "Updated description."

table = client.update_table(table, ["description"])  # API request

assert table.description == "Updated description."

테이블의 만료 시간 업데이트

데이터세트 수준에서 기본 테이블 만료 시간을 설정하거나 테이블을 만들 때 테이블 만료 시간을 설정할 수 있습니다. 테이블 만료 시간을 '수명' 또는 TTL이라고도 합니다.

테이블이 만료되면 포함된 모든 데이터와 함께 테이블이 삭제됩니다. 필요한 경우 데이터 세트에 지정된 시간 이동 창 내에 만료된 테이블 삭제를 취소할 수 있습니다. 자세한 내용은 삭제된 테이블 복원을 참조하세요.

테이블을 만들 때 만료 시간을 설정하면 데이터 세트의 기본 테이블 만료 시간은 무시됩니다. 데이터 세트 수준에서 기본 테이블 만료 시간을 설정하지 않고 테이블을 만들 때 테이블 만료 시간을 설정하지 않으면, 테이블이 만료되지 않으므로 수동으로 삭제해야 합니다.

테이블이 생성된 후 언제라도 다음 방법을 사용하여 테이블의 만료 시간을 업데이트할 수 있습니다.

  • 콘솔 사용
  • 데이터 정의 언어(DDL) ALTER TABLE 문 사용
  • bq 명령줄 도구의 bq update 명령어 사용
  • tables.patch API 메서드 호출
  • 클라이언트 라이브러리 사용

테이블의 만료 시간을 업데이트하려면 다음 안내를 따르세요.

콘솔

콘솔을 사용하여 테이블을 만들 때는 만료 시간을 추가할 수 없습니다. 테이블이 생성된 후 테이블 세부정보 페이지에서 테이블 만료 시간을 추가하거나 업데이트할 수 있습니다.

  1. 탐색기 패널에서 프로젝트와 데이터 세트를 펼친 후 테이블을 선택합니다.

  2. 세부정보 패널에서 세부정보를 클릭합니다.

  3. 테이블 정보 옆에 있는 연필 아이콘을 클릭합니다.

  4. 테이블 만료에서 날짜 지정을 선택합니다. 그런 다음 캘린더 위젯을 사용하여 만료일을 선택합니다.

  5. 업데이트를 클릭하여 저장합니다. 업데이트된 만료 시간이 테이블 정보 섹션에 나타납니다.

SQL

ALTER TABLE SET OPTIONS을 사용합니다. 다음 예시에서는 mytable이라는 테이블의 만료 시간을 업데이트합니다.

  1. 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력합니다.

    ALTER TABLE mydataset.mytable
      SET OPTIONS (
        -- Sets table expiration to timestamp 2025-02-03 12:34:56
        expiration_timestamp = TIMESTAMP '2025-02-03 12:34:56');
    

  3. 실행을 클릭합니다.

쿼리를 실행하는 방법에 대한 자세한 내용은 대화형 쿼리 실행을 참조하세요.

bq

bq update 명령어를 --expiration 플래그와 함께 실행합니다. 기본 프로젝트가 아닌 다른 프로젝트의 테이블을 업데이트하려면 프로젝트 ID를 project_id:dataset 형식으로 데이터 세트 이름에 추가합니다.

bq update \
--expiration integer \
project_id:dataset.table

다음을 바꿉니다.

  • integer: 테이블의 기본 수명(초)입니다. 최솟값은 3,600초(1시간)입니다. 만료 시간은 현재 시간과 정수 값을 더한 값으로 계산됩니다. 0을 지정하면 테이블 만료 시간이 삭제되고 테이블이 만료되지 않습니다. 만료되지 않은 테이블은 수동으로 삭제해야 합니다.
  • project_id: 프로젝트 ID입니다.
  • dataset: 업데이트할 테이블이 포함된 데이터 세트의 이름입니다.
  • table: 업데이트할 테이블의 이름입니다.

예를 들면 다음과 같습니다.

mydataset 데이터 세트에서 mytable 테이블의 만료 시간을 5일(432,000초)로 업데이트하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트에 있습니다.

bq update --expiration 432000 mydataset.mytable

mydataset 데이터 세트에서 mytable 테이블의 만료 시간을 5일(432,000초)로 업데이트하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트가 아닌 myotherproject 프로젝트에 있습니다.

bq update --expiration 432000 myotherproject:mydataset.mytable

API

tables.patch 메서드를 호출하고 테이블 리소스expirationTime 속성을 사용하여 테이블 만료 시간을 업데이트합니다(밀리초 단위). tables.update 메서드는 전체 테이블 리소스를 바꾸기 때문에 tables.patch 메서드를 사용하는 것이 좋습니다.

Go

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 BigQuery Go API 참조 문서를 확인하세요.

import (
	"context"
	"fmt"
	"time"

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

// updateTableExpiration demonstrates setting the table expiration of a table to a specific point in time
// in the future, at which time it will be deleted.
func updateTableExpiration(projectID, datasetID, tableID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// tableID := "mytable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	tableRef := client.Dataset(datasetID).Table(tableID)
	meta, err := tableRef.Metadata(ctx)
	if err != nil {
		return err
	}
	update := bigquery.TableMetadataToUpdate{
		ExpirationTime: time.Now().Add(time.Duration(5*24) * time.Hour), // table expiration in 5 days.
	}
	if _, err = tableRef.Update(ctx, update, meta.ETag); err != nil {
		return err
	}
	return nil
}

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Table;
import java.util.concurrent.TimeUnit;

public class UpdateTableExpiration {

  public static void runUpdateTableExpiration() {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    // Update table expiration to one day.
    Long newExpiration = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);
    updateTableExpiration(datasetName, tableName, newExpiration);
  }

  public static void updateTableExpiration(
      String datasetName, String tableName, Long newExpiration) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      Table table = bigquery.getTable(datasetName, tableName);
      bigquery.update(table.toBuilder().setExpirationTime(newExpiration).build());

      System.out.println("Table expiration updated successfully to " + newExpiration);
    } catch (BigQueryException e) {
      System.out.println("Table expiration was not updated \n" + e.toString());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 BigQuery Node.js API 참조 문서를 확인하세요.

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function updateTableExpiration() {
  // Updates a table's expiration.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = 'my_dataset', // Existing dataset
  // const tableId = 'my_table', // Existing table
  // const expirationTime = Date.now() + 1000 * 60 * 60 * 24 * 5 // 5 days from current time in ms

  // Retreive current table metadata
  const table = bigquery.dataset(datasetId).table(tableId);
  const [metadata] = await table.getMetadata();

  // Set new table expiration to 5 days from current time
  metadata.expirationTime = expirationTime.toString();
  const [apiResponse] = await table.setMetadata(metadata);

  const newExpirationTime = apiResponse.expirationTime;
  console.log(`${tableId} expiration: ${newExpirationTime}`);
}

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.

Table.expires 속성을 구성하고 Client.update_table()을 호출하여 업데이트를 API로 보냅니다.
import datetime

# from google.cloud import bigquery
# client = bigquery.Client()
# project = client.project
# dataset_ref = bigquery.DatasetReference(project, dataset_id)
# table_ref = dataset_ref.table('my_table')
# table = client.get_table(table_ref)  # API request

assert table.expires is None

# set table to expire 5 days from now
expiration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
    days=5
)
table.expires = expiration
table = client.update_table(table, ["expires"])  # API request

# expiration is stored in milliseconds
margin = datetime.timedelta(microseconds=1000)
assert expiration - margin <= table.expires <= expiration + margin

데이터 세트의 기본 파티션 만료 시간을 업데이트하려면 다음 안내를 따르세요.

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import java.util.concurrent.TimeUnit;

// Sample to update partition expiration on a dataset.
public class UpdateDatasetPartitionExpiration {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    // Set the default partition expiration (applies to new tables, only) in
    // milliseconds. This example sets the default expiration to 90 days.
    Long newExpiration = TimeUnit.MILLISECONDS.convert(90, TimeUnit.DAYS);
    updateDatasetPartitionExpiration(datasetName, newExpiration);
  }

  public static void updateDatasetPartitionExpiration(String datasetName, Long newExpiration) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      Dataset dataset = bigquery.getDataset(datasetName);
      bigquery.update(dataset.toBuilder().setDefaultPartitionExpirationMs(newExpiration).build());
      System.out.println(
          "Dataset default partition expiration updated successfully to " + newExpiration);
    } catch (BigQueryException e) {
      System.out.println("Dataset partition expiration was not updated \n" + e.toString());
    }
  }
}

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.


from google.cloud import bigquery

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

# TODO(developer): Set dataset_id to the ID of the dataset to fetch.
# dataset_id = 'your-project.your_dataset'

dataset = client.get_dataset(dataset_id)  # Make an API request.

# Set the default partition expiration (applies to new tables, only) in
# milliseconds. This example sets the default expiration to 90 days.
dataset.default_partition_expiration_ms = 90 * 24 * 60 * 60 * 1000

dataset = client.update_dataset(
    dataset, ["default_partition_expiration_ms"]
)  # Make an API request.

print(
    "Updated dataset {}.{} with new default partition expiration {}".format(
        dataset.project, dataset.dataset_id, dataset.default_partition_expiration_ms
    )
)

테이블의 스키마 정의 업데이트

테이블의 스키마 정의 업데이트에 대한 자세한 내용은 테이블 스키마 수정을 참조하세요.

테이블 이름 바꾸기

테이블을 만든 후에 ALTER TABLE RENAME TO을 사용하여 테이블 이름을 변경할 수 있습니다. 다음 예시에서는 mytable 이름을 mynewtable로 바꿉니다.

ALTER TABLE mydataset.mytable
RENAME TO mynewtable;

테이블 이름 바꾸기 제한사항

  • 데이터 스트리밍이 있는 테이블의 이름을 변경하려면 스트리밍을 중지하고 BigQuery에서 스트리밍이 사용 중이지 않음을 알릴 때까지 기다려야 합니다.
  • 일반적으로 마지막 스트리밍 작업으로부터 72시간 이내에 테이블 이름을 바꿀 수 있지만 더 오래 걸릴 수 있습니다.

테이블 복사

이 섹션에서는 테이블의 전체 사본을 만드는 방법을 설명합니다. 다른 유형의 테이블 사본에 대한 자세한 내용은 테이블 클론테이블 스냅샷을 참조하세요.

다음 방법으로 테이블을 복사할 수 있습니다.

  • 콘솔을 사용합니다.
  • bq cp 명령어를 사용합니다.
  • 데이터 정의 언어(DDL) CREATE TABLE COPY 문을 사용합니다.
  • jobs.insert API 메서드를 호출하고 copy 작업을 구성합니다.
  • 클라이언트 라이브러리를 사용합니다.

테이블 복사 제한사항

테이블 복사 작업에는 다음과 같은 제한사항이 적용됩니다.

  • 테이블을 복사할 때 대상 테이블 이름은 테이블을 만들 때와 동일한 명명 규칙을 따라야 합니다.
  • 테이블 복사본에는 복사 작업에 대한 BigQuery 제한이 적용됩니다.
  • 콘솔을 사용하여 테이블을 복사할 때는 대상 데이터 세트의 기존 테이블을 덮어쓸 수 없습니다. 테이블 이름은 대상 데이터 세트 내에서 고유해야 합니다.
  • 테이블을 복사할 때 대상 데이터 세트는 복사할 테이블이 포함되는 데이터 세트와 같은 위치에 있어야 합니다. 예를 들어 EU 기반 데이터세트의 테이블을 복사해 US 기반 데이터세트에 쓸 수 없습니다.
  • 대상 테이블로 여러 소스 테이블 복사는 콘솔에서 지원되지 않습니다.
  • API 또는 bq 명령줄 도구를 사용하여 대상 테이블로 여러 소스 테이블을 복사할 때는 모든 소스 테이블의 스키마가 동일해야 합니다.
  • BigQuery가 테이블을 복사하는 데 걸리는 시간은 기본 스토리지가 동적으로 관리되기 때문에 실행마다 크게 다를 수 있습니다.
  • 소스 테이블보다 열이 많고 추가 열에 기본값이 포함된 대상 테이블로 소스 테이블을 복사하고 연결할 수 없습니다.

필수 권한

이 문서의 태스크를 수행하려면 다음 권한이 필요합니다.

테이블 및 파티션 복사 권한

테이블 및 파티션을 복사하려면 소스 및 대상 데이터 세트에 대한 IAM 권한이 필요합니다.

  • 소스 데이터 세트에는 다음이 필요합니다.

    • bigquery.tables.get
    • bigquery.tables.getData
  • 대상 데이터 세트에는 다음이 필요합니다.

    • bigquery.tables.create: 이 권한을 사용하면 대상 데이터 세트에서 테이블 또는 파티션의 복사본을 만들 수 있습니다.

다음과 같은 사전 정의된 각 IAM 역할에는 테이블 및 파티션을 복사하는 데 필요한 권한이 포함되어 있습니다.

  • roles/bigquery.dataEditor
  • roles/bigquery.dataOwner
  • roles/bigquery.admin

복사 작업 실행 권한

복사 작업을 실행하려면 bigquery.jobs.create IAM 권한이 필요합니다.

다음과 같은 사전 정의된 각 IAM 역할에는 복사 작업을 실행하는 데 필요한 권한이 포함되어 있습니다.

  • roles/bigquery.user
  • roles/bigquery.jobUser
  • roles/bigquery.admin

또한 bigquery.datasets.create 권한이 있으면 만드는 데이터 세트에서 테이블과 파티션을 복사할 수 있습니다. 또한 대상 데이터 세트에 대한 액세스 권한이 필요합니다.

BigQuery의 IAM 역할과 권한에 대한 자세한 내용은 사전 정의된 역할 및 권한을 참조하세요.

단일 소스 테이블 복사

다음 방법으로 단일 테이블을 복사할 수 있습니다.

  • 콘솔 사용
  • bq 명령줄 도구의 bq cp 명령어 사용
  • 데이터 정의 언어(DDL) CREATE TABLE COPY 문 사용
  • jobs.insert API 메서드 호출, copy 작업 구성, sourceTable 속성 지정
  • 클라이언트 라이브러리 사용

콘솔 및 CREATE TABLE COPY 문에서는 복사 작업 하나에 소스 테이블과 대상 테이블 각각 하나만 지원합니다. 대상 테이블 하나에 소스 파일 여러 개를 복사하려면 bq 명령줄 도구나 API를 사용해야 합니다.

단일 원본 테이블을 복사하는 방법:

콘솔

  1. 탐색기 패널에서 프로젝트와 데이터 세트를 펼친 후 테이블을 선택합니다.

  2. 세부정보 패널에서 테이블 복사를 클릭합니다.

  3. 테이블 복사 대화상자의 대상에서 다음을 수행합니다.

    • 프로젝트 이름에서 복사된 테이블을 저장할 프로젝트를 선택합니다.
    • 데이터세트 이름에서 복사된 테이블을 저장할 데이터세트를 선택합니다. 소스 데이터세트와 대상 데이터세트는 같은 위치에 있어야 합니다.
    • 테이블 이름에 새 테이블 이름을 입력합니다. 대상 데이터세트 내에서 고유한 이름이어야 합니다. 콘솔을 사용하여 대상 데이터 세트의 기존 테이블을 덮어쓸 수 없습니다. 테이블 이름 요구사항에 대한 자세한 내용은 테이블 이름 지정을 참조하세요.
  4. 복사를 클릭하여 복사 작업을 시작합니다.

SQL

CREATE TABLE COPY을 사용하여 table1이라는 테이블을 table1copy라는 새 테이블에 복사합니다.

  1. 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력합니다.

    CREATE TABLE myproject.mydataset.table1copy
    COPY myproject.mydataset.table1;
    

  3. 실행을 클릭합니다.

쿼리를 실행하는 방법에 대한 자세한 내용은 대화형 쿼리 실행을 참조하세요.

bq

bq cp 명령어를 실행합니다. 선택적 플래그를 사용하면 대상 테이블의 쓰기 처리를 제어할 수 있습니다.

  • -a 또는 --append_table은 소스 테이블의 데이터를 대상 데이터세트의 기존 테이블에 추가합니다.
  • -f 또는 --force는 대상 데이터세트의 기존 테이블을 덮어쓰며 확인 메시지를 표시하지 않습니다.
  • -n 또는 --no_clobber는 테이블이 대상 데이터세트에 있으면 Table 'project_id:dataset.table' already exists, skipping. 오류 메시지를 반환합니다. -n을 지정하지 않으면 기본 동작으로 대상 테이블을 바꿀지 묻는 메시지가 표시됩니다.
  • --destination_kms_key는 대상 테이블을 암호화하는 데 사용되는 고객 관리 Cloud KMS 키입니다.

여기서는 --destination_kms_key를 설명하지 않습니다. 자세한 내용은 Cloud Key Management Service 키로 데이터 보호를 참조하세요.

소스 데이터 세트 또는 대상 데이터 세트가 기본 프로젝트가 아닌 다른 프로젝트에 있으면 프로젝트 ID를 project_id:dataset 형식으로 데이터 세트 이름에 추가합니다.

(선택사항) --location 플래그를 지정하고 값을 사용자 위치로 설정합니다.

bq --location=location cp \
-a -f -n \
project_id:dataset.source_table \
project_id:dataset.destination_table

다음을 바꿉니다.

  • location: 위치의 이름입니다. --location 플래그는 선택사항입니다. 예를 들어 도쿄 리전에서 BigQuery를 사용한다면 플래그 값을 asia-northeast1로 설정할 수 있습니다. .bigqueryrc 파일을 사용하여 위치 기본값을 설정할 수 있습니다.
  • project_id: 프로젝트 ID입니다.
  • dataset: 소스 또는 대상 데이터 세트의 이름입니다.
  • source_table: 복사할 테이블입니다.
  • destination_table: 대상 데이터 세트의 테이블 이름입니다.

예를 들면 다음과 같습니다.

mydataset.mytable 테이블을 mydataset2.mytable2 테이블에 복사하려면 다음 명령어를 입력합니다. 두 데이터세트 모두 기본 프로젝트에 있고,

bq cp mydataset.mytable mydataset2.mytable2

mydataset.mytable 테이블을 복사하고 이름이 같은 대상 테이블을 덮어쓰려면 다음 명령어를 입력합니다. 소스 데이터세트는 기본 프로젝트에 있고 대상 데이터 세트는 myotherproject 프로젝트에 있습니다. -f 단축키를 사용하면 확인 메시지 없이 대상 테이블을 덮어쓸 수 있습니다.

bq cp -f \
mydataset.mytable \
myotherproject:myotherdataset.mytable

mydataset.mytable 테이블을 복사하고 대상 데이터 세트에 이름이 같은 테이블이 있는 경우에 오류를 반환하려면 다음 명령어를 입력합니다. 소스 데이터세트는 기본 프로젝트에 있고 대상 데이터 세트는 myotherproject 프로젝트에 있습니다. -n 단축키를 사용하면 이름이 같은 테이블을 덮어쓰지 않습니다.

bq cp -n \
mydataset.mytable \
myotherproject:myotherdataset.mytable

mydataset.mytable 테이블을 복사하고 이름이 같은 대상 테이블에 데이터를 추가하려면 다음 명령어를 입력합니다. 소스 데이터세트는 기본 프로젝트에 있고 대상 데이터 세트는 myotherproject 프로젝트에 있습니다. - a 단축키를 사용하면 대상 테이블에 추가할 수 있습니다.

bq cp -a mydataset.mytable myotherproject:myotherdataset.mytable

API

bigquery.jobs.insert 메서드를 호출하고 copy 작업을 구성하여 API를 통해 기존 테이블을 복사할 수 있습니다. 작업 리소스jobReference 섹션에 있는 location 속성에 사용자 위치를 지정합니다.

작업 구성에 다음 값을 지정해야 합니다.

"copy": {
      "sourceTable": {       // Required
        "projectId": string, // Required
        "datasetId": string, // Required
        "tableId": string    // Required
      },
      "destinationTable": {  // Required
        "projectId": string, // Required
        "datasetId": string, // Required
        "tableId": string    // Required
      },
      "createDisposition": string,  // Optional
      "writeDisposition": string,   // Optional
    },

여기서 sourceTable은 복사할 테이블의 정보를 제공하고, destinationTable은 새 테이블의 정보를 제공합니다. createDisposition은 테이블이 없을 때 테이블 생성 여부를 지정하고, writeDisposition은 기존 테이블 덮어쓰기 또는 기존 테이블에 추가 여부를 지정합니다.

C#

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 C# 설정 안내를 따르세요. 자세한 내용은 BigQuery C# API 참조 문서를 확인하세요.


using Google.Apis.Bigquery.v2.Data;
using Google.Cloud.BigQuery.V2;
using System;

public class BigQueryCopyTable
{
    public void CopyTable(
        string projectId = "your-project-id",
        string destinationDatasetId = "your_dataset_id"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        TableReference sourceTableRef = new TableReference()
        {
            TableId = "shakespeare",
            DatasetId = "samples",
            ProjectId = "bigquery-public-data"
        };
        TableReference destinationTableRef = client.GetTableReference(
            destinationDatasetId, "destination_table");
        BigQueryJob job = client.CreateCopyJob(
            sourceTableRef, destinationTableRef)
            .PollUntilCompleted();  // Wait for the job to complete.
        // Retrieve destination table
        BigQueryTable destinationTable = client.GetTable(destinationTableRef);
        Console.WriteLine(
            $"Copied {destinationTable.Resource.NumRows} rows from table "
            + $"{sourceTableRef.DatasetId}.{sourceTableRef.TableId} "
            + $"to {destinationTable.FullyQualifiedId}."
        );
    }
}

Go

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 BigQuery Go API 참조 문서를 확인하세요.

import (
	"context"
	"fmt"

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

// copyTable demonstrates copying a table from a source to a destination, and
// allowing the copy to overwrite existing data by using truncation.
func copyTable(projectID, datasetID, srcID, dstID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// srcID := "sourcetable"
	// dstID := "destinationtable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	dataset := client.Dataset(datasetID)
	copier := dataset.Table(dstID).CopierFrom(dataset.Table(srcID))
	copier.WriteDisposition = bigquery.WriteTruncate
	job, err := copier.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
	}
	return nil
}

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.CopyJobConfiguration;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.TableId;

public class CopyTable {

  public static void runCopyTable() {
    // TODO(developer): Replace these variables before running the sample.
    String destinationDatasetName = "MY_DESTINATION_DATASET_NAME";
    String destinationTableId = "MY_DESTINATION_TABLE_NAME";
    String sourceDatasetName = "MY_SOURCE_DATASET_NAME";
    String sourceTableId = "MY_SOURCE_TABLE_NAME";

    copyTable(sourceDatasetName, sourceTableId, destinationDatasetName, destinationTableId);
  }

  public static void copyTable(
      String sourceDatasetName,
      String sourceTableId,
      String destinationDatasetName,
      String destinationTableId) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      TableId sourceTable = TableId.of(sourceDatasetName, sourceTableId);
      TableId destinationTable = TableId.of(destinationDatasetName, destinationTableId);

      // For more information on CopyJobConfiguration see:
      // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/bigquery/JobConfiguration.html
      CopyJobConfiguration configuration =
          CopyJobConfiguration.newBuilder(destinationTable, sourceTable).build();

      // For more information on Job see:
      // https://googleapis.dev/java/google-cloud-clients/latest/index.html?com/google/cloud/bigquery/package-summary.html
      Job job = bigquery.create(JobInfo.of(configuration));

      // Blocks until this job completes its execution, either failing or succeeding.
      Job completedJob = job.waitFor();
      if (completedJob == null) {
        System.out.println("Job not executed since it no longer exists.");
        return;
      } else if (completedJob.getStatus().getError() != null) {
        System.out.println(
            "BigQuery was unable to copy table due to an error: \n" + job.getStatus().getError());
        return;
      }
      System.out.println("Table copied successfully.");
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Table copying job was interrupted. \n" + e.toString());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 BigQuery Node.js API 참조 문서를 확인하세요.

// Import the Google Cloud client library and create a client
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function copyTable() {
  // Copies src_dataset:src_table to dest_dataset:dest_table.

  /**
   * TODO(developer): Uncomment the following lines before running the sample
   */
  // const srcDatasetId = "my_src_dataset";
  // const srcTableId = "my_src_table";
  // const destDatasetId = "my_dest_dataset";
  // const destTableId = "my_dest_table";

  // Copy the table contents into another table
  const [job] = await bigquery
    .dataset(srcDatasetId)
    .table(srcTableId)
    .copy(bigquery.dataset(destDatasetId).table(destTableId));

  console.log(`Job ${job.id} completed.`);

  // Check the job's status for errors
  const errors = job.status.errors;
  if (errors && errors.length > 0) {
    throw errors;
  }
}

PHP

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 PHP 설정 안내를 따르세요. 자세한 내용은 BigQuery PHP API 참조 문서를 참조하세요.

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

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $datasetId = 'The BigQuery dataset ID';
// $sourceTableId   = 'The BigQuery table ID to copy from';
// $destinationTableId = 'The BigQuery table ID to copy to';

$bigQuery = new BigQueryClient([
    'projectId' => $projectId,
]);
$dataset = $bigQuery->dataset($datasetId);
$sourceTable = $dataset->table($sourceTableId);
$destinationTable = $dataset->table($destinationTableId);
$copyConfig = $sourceTable->copy($destinationTable);
$job = $sourceTable->runJob($copyConfig);

// poll the job until it is complete
$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);
    }
});
// check if the job has errors
if (isset($job->info()['status']['errorResult'])) {
    $error = $job->info()['status']['errorResult']['message'];
    printf('Error running job: %s' . PHP_EOL, $error);
} else {
    print('Table copied successfully' . PHP_EOL);
}

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.


from google.cloud import bigquery

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

# TODO(developer): Set source_table_id to the ID of the original table.
# source_table_id = "your-project.source_dataset.source_table"

# TODO(developer): Set destination_table_id to the ID of the destination table.
# destination_table_id = "your-project.destination_dataset.destination_table"

job = client.copy_table(source_table_id, destination_table_id)
job.result()  # Wait for the job to complete.

print("A copy of the table created.")

여러 소스 테이블 복사

다음 방법으로 대상 테이블에 여러 소스 테이블을 복사할 수 있습니다.

  • bq 명령줄 도구의 bq cp 명령어 사용
  • jobs.insert 메서드 호출, copy 작업 구성, sourceTables 속성 지정
  • 클라이언트 라이브러리 사용

모든 소스 테이블은 스키마가 같아야 하며 대상 테이블은 하나만 허용됩니다.

소스 테이블은 쉼표로 구분된 목록으로 지정해야 합니다. 여러 소스 테이블을 복사할 때는 와일드 카드를 사용할 수 없습니다.

소스 테이블을 여러 개 복사하려면 다음 중 하나를 선택합니다.

bq

bq cp 명령어를 실행하고 소스 테이블 여러 개를 쉼표로 구분된 목록으로 포함합니다. 선택적 플래그를 사용하면 대상 테이블의 쓰기 처리를 제어할 수 있습니다.

  • -a 또는 --append_table은 소스 테이블의 데이터를 대상 데이터세트의 기존 테이블에 추가합니다.
  • -f 또는 --force는 대상 데이터세트의 기존 대상 테이블을 덮어쓰고 확인 메시지를 표시하지 않습니다.
  • -n 또는 --no_clobber는 테이블이 대상 데이터세트에 있으면 Table 'project_id:dataset.table' already exists, skipping. 오류 메시지를 반환합니다. -n을 지정하지 않으면 기본 동작으로 대상 테이블을 대체할지 묻는 메시지가 표시됩니다.
  • --destination_kms_key는 대상 테이블을 암호화하는 데 사용되는 고객 관리 Cloud Key Management Service 키입니다.

여기서는 --destination_kms_key를 설명하지 않습니다. 자세한 내용은 Cloud Key Management Service 키로 데이터 보호를 참조하세요.

소스 데이터 세트 또는 대상 데이터 세트가 기본 프로젝트가 아닌 다른 프로젝트에 있으면 프로젝트 ID를 project_id:dataset 형식으로 데이터 세트 이름에 추가합니다.

(선택사항) --location 플래그를 지정하고 값을 사용자 위치로 설정합니다.

bq --location=location cp \
-a -f -n \
project_id:dataset.source_table,project_id:dataset.source_table \
project_id:dataset.destination_table

다음을 바꿉니다.

  • location: 위치의 이름입니다. --location 플래그는 선택사항입니다. 예를 들어 도쿄 리전에서 BigQuery를 사용한다면 플래그 값을 asia-northeast1로 설정할 수 있습니다. .bigqueryrc 파일을 사용하여 위치 기본값을 설정할 수 있습니다.
  • project_id: 프로젝트 ID입니다.
  • dataset: 소스 또는 대상 데이터 세트의 이름입니다.
  • source_table: 복사할 테이블입니다.
  • destination_table: 대상 데이터 세트의 테이블 이름입니다.

예를 들면 다음과 같습니다.

mydataset.mytable 테이블과 mydataset.mytable2 테이블을 mydataset2.tablecopy 테이블에 복사하려면 다음 명령어를 입력합니다. 데이터세트 모두 기본 프로젝트에 있습니다.

bq cp \
mydataset.mytable,mydataset.mytable2 \
mydataset2.tablecopy

mydataset.mytable 테이블과 mydataset.mytable2 테이블을 myotherdataset.mytable 테이블에 복사하고 이름이 같은 대상 테이블을 덮어쓰려면 다음 명령어를 입력합니다. 대상 데이터 세트는 기본 프로젝트가 아닌 myotherproject 프로젝트에 있습니다. -f 단축키를 사용하면 확인 메시지 없이 대상 테이블을 덮어쓸 수 있습니다.

bq cp -f \
mydataset.mytable,mydataset.mytable2 \
myotherproject:myotherdataset.mytable

myproject:mydataset.mytable 테이블과 myproject:mydataset.mytable2 테이블을 복사하고 대상 데이터 세트에 이름이 같은 테이블이 있는 경우 오류를 반환하려면 다음 명령어를 입력합니다. 대상 데이터 세트는 myotherproject 프로젝트에 있습니다. -n 단축키를 사용하면 이름이 같은 테이블을 덮어쓰지 않습니다.

bq cp -n \
myproject:mydataset.mytable,myproject:mydataset.mytable2 \
myotherproject:myotherdataset.mytable

mydataset.mytable 테이블과 mydataset.mytable2 테이블을 복사하고 이름이 같은 대상 테이블에 데이터를 추가하려면 다음 명령어를 입력합니다. 소스 데이터세트는 기본 프로젝트에 있고 대상 데이터 세트는 myotherproject 프로젝트에 있습니다. -a 단축키를 사용하면 대상 테이블에 추가할 수 있습니다.

bq cp -a \
mydataset.mytable,mydataset.mytable2 \
myotherproject:myotherdataset.mytable

API

API를 사용하여 테이블 여러 개를 복사하려면 jobs.insert 메서드를 호출하고, 테이블 copy 작업을 구성한 후 sourceTables 속성을 지정합니다.

작업 리소스jobReference 섹션에 있는 location 속성에 사용자 리전을 지정합니다.

Go

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 BigQuery Go API 참조 문서를 확인하세요.

import (
	"context"
	"fmt"

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

// copyMultiTable demonstrates using a copy job to copy multiple source tables into a single destination table.
func copyMultiTable(projectID, srcDatasetID string, srcTableIDs []string, dstDatasetID, dstTableID string) error {
	// projectID := "my-project-id"
	// srcDatasetID := "sourcedataset"
	// srcTableIDs := []string{"table1","table2"}
	// dstDatasetID = "destinationdataset"
	// dstTableID = "destinationtable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	srcDataset := client.Dataset(srcDatasetID)
	dstDataset := client.Dataset(dstDatasetID)
	var tableRefs []*bigquery.Table
	for _, v := range srcTableIDs {
		tableRefs = append(tableRefs, srcDataset.Table(v))
	}
	copier := dstDataset.Table(dstTableID).CopierFrom(tableRefs...)
	copier.WriteDisposition = bigquery.WriteTruncate
	job, err := copier.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
	}
	return nil
}

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.CopyJobConfiguration;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.TableId;
import java.util.Arrays;

public class CopyMultipleTables {

  public static void runCopyMultipleTables() {
    // TODO(developer): Replace these variables before running the sample.
    String destinationDatasetName = "MY_DATASET_NAME";
    String destinationTableId = "MY_TABLE_NAME";
    copyMultipleTables(destinationDatasetName, destinationTableId);
  }

  public static void copyMultipleTables(String destinationDatasetName, String destinationTableId) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      TableId destinationTable = TableId.of(destinationDatasetName, destinationTableId);

      // For more information on CopyJobConfiguration see:
      // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/bigquery/JobConfiguration.html
      CopyJobConfiguration configuration =
          CopyJobConfiguration.newBuilder(
                  destinationTable,
                  Arrays.asList(
                      TableId.of(destinationDatasetName, "table1"),
                      TableId.of(destinationDatasetName, "table2")))
              .build();

      // For more information on Job see:
      // https://googleapis.dev/java/google-cloud-clients/latest/index.html?com/google/cloud/bigquery/package-summary.html
      Job job = bigquery.create(JobInfo.of(configuration));

      // Blocks until this job completes its execution, either failing or succeeding.
      Job completedJob = job.waitFor();
      if (completedJob == null) {
        System.out.println("Job not executed since it no longer exists.");
        return;
      } else if (completedJob.getStatus().getError() != null) {
        System.out.println(
            "BigQuery was unable to copy tables due to an error: \n" + job.getStatus().getError());
        return;
      }
      System.out.println("Table copied successfully.");
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Table copying job was interrupted. \n" + e.toString());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 BigQuery Node.js API 참조 문서를 확인하세요.

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function copyTableMultipleSource() {
  // Copy multiple source tables to a given destination.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = "my_dataset";
  // sourceTable = 'my_table';
  // destinationTable = 'testing';

  // Create a client
  const dataset = bigquery.dataset(datasetId);

  const metadata = {
    createDisposition: 'CREATE_NEVER',
    writeDisposition: 'WRITE_TRUNCATE',
  };

  // Create table references
  const table = dataset.table(sourceTable);
  const yourTable = dataset.table(destinationTable);

  // Copy table
  const [apiResponse] = await table.copy(yourTable, metadata);
  console.log(apiResponse.configuration.copy);
}

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.


from google.cloud import bigquery

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

# TODO(developer): Set dest_table_id to the ID of the destination table.
# dest_table_id = "your-project.your_dataset.your_table_name"

# TODO(developer): Set table_ids to the list of the IDs of the original tables.
# table_ids = ["your-project.your_dataset.your_table_name", ...]

job = client.copy_table(table_ids, dest_table_id)  # Make an API request.
job.result()  # Wait for the job to complete.

print("The tables {} have been appended to {}".format(table_ids, dest_table_id))

테이블 삭제

다음 방법으로 테이블을 삭제할 수 있습니다.

  • 콘솔 사용
  • 데이터 정의 언어(DDL) DROP TABLE 문 사용
  • bq 명령줄 도구의 bq rm 명령어 사용
  • tables.delete API 메서드 호출
  • 클라이언트 라이브러리 사용

현재는 한 번에 테이블 한 개만 삭제할 수 있습니다.

테이블을 삭제하면 테이블의 데이터도 모두 삭제됩니다. 지정된 기간이 경과한 후 테이블을 자동으로 삭제하려면 데이터세트의 기본 테이블 만료 시간을 설정하거나 테이블을 만들 때 만료 시간을 설정합니다.

필수 권한

테이블을 삭제하려면 다음 IAM 권한이 필요합니다.

  • bigquery.tables.delete
  • bigquery.tables.get

다음과 같은 사전 정의된 각 IAM 역할에는 테이블을 삭제하는 데 필요한 권한이 포함되어 있습니다.

  • roles/bigquery.dataEditor
  • roles/bigquery.dataOwner
  • roles/bigquery.admin

또한 bigquery.datasets.create 권한이 있으면 만드는 데이터 세트의 테이블을 삭제할 수 있습니다.

BigQuery의 IAM 역할과 권한에 대한 자세한 내용은 사전 정의된 역할 및 권한을 참조하세요.

테이블 삭제

테이블을 삭제하는 방법:

콘솔

  1. 탐색기 패널에서 프로젝트와 데이터 세트를 펼친 후 테이블을 선택합니다.

  2. 세부정보 패널에서 테이블 삭제를 클릭합니다.

  3. 대화상자에 "delete"를 입력하고 삭제를 클릭하여 확인합니다.

SQL

DROP TABLE을 사용합니다. 다음 예시에서는 mytable이라는 테이블을 삭제합니다.

  1. 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력합니다.

    DROP TABLE mydataset.mytable;
    

  3. 실행을 클릭합니다.

쿼리를 실행하는 방법에 대한 자세한 내용은 대화형 쿼리 실행을 참조하세요.

bq

bq rm 명령어를 --table 플래그(또는 -t 단축키)와 함께 사용하여 테이블을 삭제합니다. bq 명령줄 도구를 사용하여 테이블을 삭제할 때 작업을 확인해야 합니다. --force 플래그(또는 -f 단축키)를 사용하면 확인 절차를 건너뛸 수 있습니다.

테이블이 기본 프로젝트가 아닌 다른 프로젝트의 데이터 세트에 있으면 프로젝트 ID를 project_id:dataset 형식으로 데이터 세트 이름에 추가합니다.

bq rm \
-f \
-t \
project_id:dataset.table

다음을 바꿉니다.

  • project_id: 프로젝트 ID입니다.
  • dataset: 테이블이 포함된 데이터 세트의 이름입니다.
  • table: 삭제할 테이블의 이름입니다.

예를 들면 다음과 같습니다.

mydataset 데이터 세트에서 mytable 테이블을 삭제하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트에 있습니다.

bq rm -t mydataset.mytable

mydataset 데이터 세트에서 mytable 테이블을 삭제하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트가 아닌 myotherproject 프로젝트에 있습니다.

bq rm -t myotherproject:mydataset.mytable

mydataset 데이터 세트에서 mytable 테이블을 삭제하려면 다음 명령어를 입력합니다. mydataset 데이터 세트는 기본 프로젝트에 있습니다. 이 명령어에서 -f 단축키를 사용하면 확인을 건너뛸 수 있습니다.

bq rm -f -t mydataset.mytable

API

tables.delete API 메서드를 호출하고 tableId 매개변수를 사용하여 삭제할 테이블을 지정합니다.

C#

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 C# 설정 안내를 따르세요. 자세한 내용은 BigQuery C# API 참조 문서를 확인하세요.


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

public class BigQueryDeleteTable
{
    public void DeleteTable(
        string projectId = "your-project-id",
        string datasetId = "your_dataset_id",
        string tableId = "your_table_id"
    )
    {
        BigQueryClient client = BigQueryClient.Create(projectId);
        client.DeleteTable(datasetId, tableId);
        Console.WriteLine($"Table {tableId} deleted.");
    }
}

Go

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 BigQuery Go API 참조 문서를 확인하세요.

import (
	"context"
	"fmt"

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

// deleteTable demonstrates deletion of a BigQuery table.
func deleteTable(projectID, datasetID, tableID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// tableID := "mytable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	table := client.Dataset(datasetID).Table(tableID)
	if err := table.Delete(ctx); err != nil {
		return err
	}
	return nil
}

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;

public class DeleteTable {

  public static void runDeleteTable() {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_NAME";
    deleteTable(datasetName, tableName);
  }

  public static void deleteTable(String datasetName, String tableName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
      boolean success = bigquery.delete(TableId.of(datasetName, tableName));
      if (success) {
        System.out.println("Table deleted successfully");
      } else {
        System.out.println("Table was not found");
      }
    } catch (BigQueryException e) {
      System.out.println("Table was not deleted. \n" + e.toString());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 BigQuery Node.js API 참조 문서를 확인하세요.

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function deleteTable() {
  // Deletes "my_table" from "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = "my_dataset";
  // const tableId = "my_table";

  // Delete the table
  await bigquery
    .dataset(datasetId)
    .table(tableId)
    .delete();

  console.log(`Table ${tableId} deleted.`);
}

PHP

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 PHP 설정 안내를 따르세요. 자세한 내용은 BigQuery PHP API 참조 문서를 참조하세요.

use Google\Cloud\BigQuery\BigQueryClient;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $datasetId = 'The BigQuery dataset ID';
// $tableId = 'The BigQuery table ID';

$bigQuery = new BigQueryClient([
    'projectId' => $projectId,
]);
$dataset = $bigQuery->dataset($datasetId);
$table = $dataset->table($tableId);
$table->delete();
printf('Deleted table %s.%s' . PHP_EOL, $datasetId, $tableId);

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.


from google.cloud import bigquery

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

# TODO(developer): Set table_id to the ID of the table to fetch.
# table_id = 'your-project.your_dataset.your_table'

# If the table does not exist, delete_table raises
# google.api_core.exceptions.NotFound unless not_found_ok is True.
client.delete_table(table_id, not_found_ok=True)  # Make an API request.
print("Deleted table '{}'.".format(table_id))

Ruby

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Ruby 설정 안내를 따르세요. 자세한 내용은 BigQuery Ruby API 참조 문서를 확인하세요.

require "google/cloud/bigquery"

def delete_table dataset_id = "my_dataset_id", table_id = "my_table_id"
  bigquery = Google::Cloud::Bigquery.new
  dataset  = bigquery.dataset dataset_id
  table    = dataset.table table_id

  table.delete

  puts "Table #{table_id} deleted."
end

삭제된 테이블 복원

테이블 만료 시간으로 인한 명시적 삭제 및 암시적 삭제를 포함하여 데이터 세트에 지정된 시간 이동 창 내에 테이블 삭제를 취소할 수 있습니다. 시간 이동 창을 구성하는 기능은 미리보기에 있습니다.

시간 이동 기간은 2~7일입니다. 시간 이동 기간이 지나면 지원 티켓 열기를 비롯한 그 어떤 방법으로도 테이블의 삭제를 취소할 수 없습니다.

만료되어 삭제된, 파티션을 나눈 테이블을 복원할 때는 수동으로 파티션을 다시 만들어야 합니다.

@<time> 시간 데코레이터를 사용하여 테이블을 새 테이블에 복사하여 삭제되었지만 아직 시간 이동 창 내의 테이블을 복원할 수 있습니다. 테이블을 복사하려면 bq 명령줄 도구 또는 클라이언트 라이브러리를 사용합니다.

콘솔

콘솔을 사용하여 테이블 삭제를 취소할 수 없습니다.

bq

테이블 삭제를 취소하려면 @<time> 스냅샷 데코레이터와 테이블 복사 작업을 사용합니다. 먼저 테이블이 있었던 시점의 UNIX 타임스탬프(밀리초 단위)를 확인합니다. 그런 다음 bq copy 명령어를 스냅샷 데코레이터와 함께 사용합니다.

예를 들어 1418864998000 시점의 mydataset.mytable 테이블을 새 테이블인 mydataset.newtable로 복사하려면 다음 명령어를 입력합니다.

bq cp mydataset.mytable@1418864998000 mydataset.newtable

(선택사항) --location 플래그를 지정하고 값을 사용자 위치로 설정합니다.

상대 오프셋을 지정할 수도 있습니다. 다음 예시에서는 1시간 전의 테이블 버전을 복사합니다.

bq cp mydataset.mytable@-3600000 mydataset.newtable

자세한 내용은 특정 시점의 테이블 복원을 참조하세요.

Go

import (
	"context"
	"fmt"
	"time"

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

// deleteAndUndeleteTable demonstrates how to recover a deleted table by copying it from a point in time
// that predates the deletion event.
func deleteAndUndeleteTable(projectID, datasetID, tableID string) error {
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// tableID := "mytable"
	ctx := context.Background()
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %v", err)
	}
	defer client.Close()

	ds := client.Dataset(datasetID)
	if _, err := ds.Table(tableID).Metadata(ctx); err != nil {
		return err
	}
	// Record the current time.  We'll use this as the snapshot time
	// for recovering the table.
	snapTime := time.Now()

	// "Accidentally" delete the table.
	if err := client.Dataset(datasetID).Table(tableID).Delete(ctx); err != nil {
		return err
	}

	// Construct the restore-from tableID using a snapshot decorator.
	snapshotTableID := fmt.Sprintf("%s@%d", tableID, snapTime.UnixNano()/1e6)
	// Choose a new table ID for the recovered table data.
	recoverTableID := fmt.Sprintf("%s_recovered", tableID)

	// Construct and run a copy job.
	copier := ds.Table(recoverTableID).CopierFrom(ds.Table(snapshotTableID))
	copier.WriteDisposition = bigquery.WriteTruncate
	job, err := copier.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
	}

	ds.Table(recoverTableID).Delete(ctx)
	return nil
}

자바

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 BigQuery 자바 API 참조 문서를 확인하세요.

import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.CopyJobConfiguration;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
import com.google.cloud.bigquery.TableId;

// Sample to undeleting a table
public class UndeleteTable {

  public static void runUndeleteTable() {
    // TODO(developer): Replace these variables before running the sample.
    String datasetName = "MY_DATASET_NAME";
    String tableName = "MY_TABLE_TABLE";
    String recoverTableName = "MY_RECOVER_TABLE_TABLE";
    undeleteTable(datasetName, tableName, recoverTableName);
  }

  public static void undeleteTable(String datasetName, String tableName, String recoverTableName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // "Accidentally" delete the table.
      bigquery.delete(TableId.of(datasetName, tableName));

      // Record the current time.  We'll use this as the snapshot time
      // for recovering the table.
      long snapTime = System.currentTimeMillis();

      // Construct the restore-from tableID using a snapshot decorator.
      String snapshotTableId = String.format("%s@%d", tableName, snapTime);

      // Construct and run a copy job.
      CopyJobConfiguration configuration =
          CopyJobConfiguration.newBuilder(
                  // Choose a new table ID for the recovered table data.
                  TableId.of(datasetName, recoverTableName),
                  TableId.of(datasetName, snapshotTableId))
              .build();

      Job job = bigquery.create(JobInfo.of(configuration));
      job = job.waitFor();
      if (job.isDone() && job.getStatus().getError() == null) {
        System.out.println("Undelete table recovered successfully.");
      } else {
        System.out.println(
            "BigQuery was unable to copy the table due to an error: \n"
                + job.getStatus().getError());
        return;
      }
    } catch (BigQueryException | InterruptedException e) {
      System.out.println("Table not found. \n" + e.toString());
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 BigQuery Node.js API 참조 문서를 확인하세요.

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

async function undeleteTable() {
  // Undeletes "my_table_to_undelete" from "my_dataset".

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const datasetId = "my_dataset";
  // const tableId = "my_table_to_undelete";
  // const recoveredTableId = "my_recovered_table";

  /**
   * TODO(developer): Choose an appropriate snapshot point as epoch milliseconds.
   * For this example, we choose the current time as we're about to delete the
   * table immediately afterwards.
   */
  const snapshotEpoch = Date.now();

  // Delete the table
  await bigquery
    .dataset(datasetId)
    .table(tableId)
    .delete();

  console.log(`Table ${tableId} deleted.`);

  // Construct the restore-from table ID using a snapshot decorator.
  const snapshotTableId = `${tableId}@${snapshotEpoch}`;

  // Construct and run a copy job.
  await bigquery
    .dataset(datasetId)
    .table(snapshotTableId)
    .copy(bigquery.dataset(datasetId).table(recoveredTableId));

  console.log(
    `Copied data from deleted table ${tableId} to ${recoveredTableId}`
  );
}

Python

이 샘플을 사용해 보기 전에 BigQuery 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 BigQuery Python API 참조 문서를 확인하세요.

import time

from google.cloud import bigquery

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

# TODO(developer): Choose a table to recover.
# table_id = "your-project.your_dataset.your_table"

# TODO(developer): Choose a new table ID for the recovered table data.
# recovered_table_id = "your-project.your_dataset.your_table_recovered"

# TODO(developer): Choose an appropriate snapshot point as epoch
# milliseconds. For this example, we choose the current time as we're about
# to delete the table immediately afterwards.
snapshot_epoch = int(time.time() * 1000)

# ...

# "Accidentally" delete the table.
client.delete_table(table_id)  # Make an API request.

# Construct the restore-from table ID using a snapshot decorator.
snapshot_table_id = "{}@{}".format(table_id, snapshot_epoch)

# Construct and run a copy job.
job = client.copy_table(
    snapshot_table_id,
    recovered_table_id,
    # Must match the source and destination tables location.
    location="US",
)  # Make an API request.

job.result()  # Wait for the job to complete.

print(
    "Copied data from deleted table {} to {}".format(table_id, recovered_table_id)
)

시간 이동 기간에 허용되는 것보다 나중에 테이블을 복원해야 할 것으로 예상되는 경우, 테이블의 테이블 스냅샷을 만듭니다. 자세한 내용은 테이블 스냅샷을 참조하세요.

테이블 보안

BigQuery에서 테이블에 대한 액세스를 제어하려면 테이블 액세스 제어 소개를 참조하세요.

다음 단계