테이블 관리

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

삭제된 테이블을 복원(또는 삭제 취소)하는 방법에 관한 자세한 내용은 삭제된 테이블 복원을 참고하세요.

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

시작하기 전에

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

테이블 속성 업데이트

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

필수 권한

테이블 속성을 업데이트하는 데 필요한 권한을 얻으려면 관리자에게 테이블에 대한 데이터 편집자(roles/bigquery.dataEditor) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 테이블 속성을 업데이트하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

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

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

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

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

테이블 설명 업데이트

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

  • Google Cloud 콘솔 사용
  • 데이터 정의 언어(DDL) ALTER TABLE 문 사용
  • bq 명령줄 도구의 bq update 명령어 사용
  • tables.patch API 메서드 호출
  • 클라이언트 라이브러리 사용
  • BigQuery의 Gemini로 설명을 생성합니다.

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

콘솔

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

  1. 왼쪽 창에서 탐색기를 클릭합니다.

    탐색기 창의 강조 표시된 버튼

    왼쪽 창이 표시되지 않으면 왼쪽 창 펼치기를 클릭하여 창을 엽니다.

  2. 탐색기 창에서 프로젝트를 펼치고 데이터 세트를 클릭한 다음 데이터 세트를 선택합니다.

  3. 개요 > 테이블을 클릭한 다음 테이블을 선택합니다.

  4. 세부정보 탭을 클릭한 다음 세부정보 수정을 클릭합니다.

  5. 설명 섹션에서 새 설명을 추가하거나 기존 설명을 수정합니다.

  6. 저장을 클릭합니다.

SQL

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

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

    BigQuery로 이동

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

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

  3. 실행을 클릭합니다.

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
    
  3. API

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

    Go

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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
    }
    

    Java

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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."

    Gemini

    데이터 인사이트를 사용하여 BigQuery의 Gemini로 테이블 설명을 생성할 수 있습니다. 데이터 통계는 데이터를 탐색, 이해, 선별하는 자동화된 방법입니다.

    설정 단계, 필요한 IAM 역할, 생성된 통계의 정확도를 높이기 위한 권장사항 등 데이터 통계에 대한 자세한 내용은 BigQuery에서 데이터 통계 생성을 참고하세요.

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

      BigQuery로 이동

    2. 왼쪽 창에서 탐색기를 클릭합니다.

      탐색기 창의 강조 표시된 버튼

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

    4. 세부정보 패널에서 스키마 탭을 클릭합니다.

    5. 생성을 클릭합니다.

      Gemini가 테이블 설명과 테이블에 관한 인사이트를 생성합니다. 정보가 채워지는 데 몇 분 정도 걸립니다. 생성된 통계는 테이블의 통계 탭에서 확인할 수 있습니다.

    6. 생성된 표 설명을 수정하고 저장하려면 다음 단계를 따르세요.

      1. 열 설명 보기를 클릭합니다.

        현재 테이블 설명과 생성된 설명이 표시됩니다.

      2. 표 설명 섹션에서 세부정보에 저장을 클릭합니다.

      3. 생성된 설명으로 현재 설명을 바꾸려면 추천 설명 복사를 클릭합니다.

      4. 필요에 따라 테이블 설명을 수정한 후 세부정보에 저장을 클릭합니다.

        표 설명이 즉시 업데이트됩니다.

      5. 설명 미리보기 패널을 닫으려면 닫기를 클릭합니다.

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

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

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

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

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

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

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

콘솔

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

  1. 왼쪽 창에서 탐색기를 클릭합니다.

    탐색기 창의 강조 표시된 버튼

  2. 탐색기 창에서 프로젝트를 펼치고 데이터 세트를 클릭한 다음 데이터 세트를 선택합니다.

  3. 개요 > 테이블을 클릭한 다음 테이블을 선택합니다.

  4. 세부정보 탭을 클릭한 다음 세부정보 수정을 클릭합니다.

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

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

SQL

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

  1. Google Cloud 콘솔에서 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

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
    
  3. API

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

    Go

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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
    }
    

    Java

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    Table.expires 속성을 구성하고 Client.update_table()을 호출하여 업데이트를 API로 보냅니다.
    # Copyright 2022 Google LLC
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     https://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    
    import datetime
    
    
    def update_table_expiration(table_id, expiration):
        orig_table_id = table_id
        orig_expiration = expiration
    
        from google.cloud import bigquery
    
        client = bigquery.Client()
    
        # TODO(dev): Change table_id to the full name of the table you want to update.
        table_id = "your-project.your_dataset.your_table_name"
    
        # TODO(dev): Set table to expire for desired days days from now.
        expiration = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
            days=5
        )
    
        table_id = orig_table_id
        expiration = orig_expiration
    
        table = client.get_table(table_id)  # Make an API request.
        table.expires = expiration
        table = client.update_table(table, ["expires"])  # API request
    
        print(f"Updated {table_id}, expires {table.expires}.")
    

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

자바

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

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

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 참고 문서를 확인하세요.

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


def update_dataset_default_partition_expiration(dataset_id: str) -> None:

    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 SET OPTIONS DDL 문을 사용하여 테이블의 기본 반올림 모드를 업데이트할 수 있습니다. 다음 예시에서는 mytable의 기본 반올림 모드를 ROUND_HALF_EVEN으로 업데이트합니다.

ALTER TABLE mydataset.mytable
SET OPTIONS (
  default_rounding_mode = "ROUND_HALF_EVEN");

테이블에 NUMERIC 또는 BIGNUMERIC 필드를 추가하고 반올림 모드를 지정하지 않으면 반올림 모드가 테이블의 기본 반올림 모드로 자동 설정됩니다. 표의 기본 반올림 모드를 변경해도 기존 필드의 반올림 모드는 변경되지 않습니다.

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

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

테이블 이름 바꾸기

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

ALTER TABLE mydataset.mytable
RENAME TO mynewtable;

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

  • 데이터 스트리밍이 있는 테이블의 이름을 바꾸려면 스트리밍을 중지하고 대기 중인 스트림을 커밋한 후 BigQuery에서 스트리밍이 사용 중이지 않음을 알릴 때까지 기다려야 합니다.
  • 일반적으로 마지막 스트리밍 작업 후 5시간이 지나면 테이블 이름을 바꿀 수 있지만 더 오래 걸릴 수 있습니다.
  • 기존 테이블 ACL과 행 액세스 정책은 보존되지만 테이블 이름 변경 중에 수행된 테이블 ACL 및 행 액세스 정책 업데이트는 보존되지 않습니다.
  • 동시에 테이블 이름을 바꾸고 해당 테이블에서 DML 문을 실행할 수는 없습니다.
  • 테이블 이름을 변경하면 테이블의 모든 Data Catalog 태그(지원 중단됨) 및 Dataplex 범용 카탈로그 측정기준이 삭제됩니다.
  • 외부 테이블의 이름을 바꿀 수 없습니다.

테이블 복사

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

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

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

테이블 복사 제한사항

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

  • 표 복사 작업을 시작한 후에는 중지할 수 없습니다. 테이블 복사 작업은 비동기식으로 실행되며 작업을 취소해도 중지되지 않습니다. 리전 간 테이블 복사에 따른 데이터 전송 및 대상 리전의 스토리지에 대한 요금도 청구됩니다.
  • 테이블을 복사할 때 대상 테이블 이름은 테이블을 만들 때와 동일한 명명 규칙을 따라야 합니다.
  • 테이블 복사본에는 복사 작업에 대한 BigQuery 제한이 적용됩니다.
  • Google Cloud 콘솔에서는 한 번에 하나씩만 테이블 복사가 지원됩니다. 대상 데이터 세트의 기존 테이블을 덮어쓸 수 없습니다. 테이블 이름은 대상 데이터 세트 내에서 고유해야 합니다.
  • 대상 테이블로 여러 소스 테이블 복사는 Google Cloud 콘솔에서 지원되지 않습니다.
  • API, bq 명령줄 도구, 클라이언트 라이브러리를 사용하여 대상 테이블로 여러 소스 테이블을 복사할 때는 모든 소스 테이블의 파티션 나누기 또는 클러스터링을 포함한 스키마가 동일해야 합니다.

    열 삭제 또는 이름 변경과 같은 특정 테이블 스키마 업데이트 시 테이블의 스키마는 동일해 보이지만 내부 표현이 다를 수 있습니다. 이로 인해 테이블 복사 작업이 Maximum limit on diverging physical schemas reached 오류와 함께 실패할 수 있습니다. 이 경우 소스 테이블의 스키마가 대상 테이블의 스키마와 정확하게 일치하도록 CREATE TABLE LIKE을 사용할 수 있습니다.

  • BigQuery가 테이블을 복사하는 데 걸리는 시간은 기본 스토리지가 동적으로 관리되기 때문에 실행마다 크게 다를 수 있습니다.

  • 소스 테이블보다 열이 많고 추가 열에 기본값이 포함된 대상 테이블로 소스 테이블을 복사하고 연결할 수 없습니다. 대신 INSERT destination_table SELECT * FROM source_table을 실행하여 데이터를 복사할 수 있습니다.

  • 복사 작업이 기존 테이블을 덮어써도 기존 테이블의 테이블 수준 액세스는 유지됩니다. 소스 테이블의 태그는 덮어쓰기된 테이블에 복사되지 않지만 기존 테이블의 태그는 유지됩니다. 하지만 리전 간에 테이블을 복사하면 기존 테이블의 태그가 삭제됩니다.

  • 복사 작업으로 새 테이블이 생성되는 경우 새 테이블에 대한 테이블 수준 액세스는 새 테이블이 생성되는 데이터 세트의 액세스 정책에 따라 결정됩니다. 또한 태그가 소스 테이블에서 새 테이블로 복사됩니다.

  • 여러 소스 테이블을 대상 테이블에 복사할 때 모든 소스 테이블에는 동일한 태그가 있어야 합니다.

필요한 역할

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

테이블 및 파티션 복사 역할

테이블 및 파티션을 복사하는 데 필요한 권한을 얻으려면 관리자에게 소스 및 대상 데이터 세트에 대한 데이터 편집자(roles/bigquery.dataEditor) IAM 역할을 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 테이블 및 파티션을 복사하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

테이블 및 파티션을 복사하려면 다음 권한이 필요합니다.

  • 소스 및 대상 데이터 세트에 대한 bigquery.tables.getData 권한
  • 소스 및 대상 데이터 세트에 대한 bigquery.tables.get 권한
  • 대상 데이터 세트에 대한 bigquery.tables.create 권한
  • 대상 데이터 세트에 대한 bigquery.tables.update 권한

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

복사 작업 실행 권한

복사 작업을 실행하는 데 필요한 권한을 얻으려면 관리자에게 소스 및 대상 데이터 세트에 대한 작업 사용자(roles/bigquery.jobUser) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 복사 작업 실행에 필요한 bigquery.jobs.create 권한이 포함되어 있습니다.

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

단일 소스 테이블 복사

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

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

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

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

콘솔

  1. 왼쪽 창에서 탐색기를 클릭합니다.

    탐색기 창의 강조 표시된 버튼

  2. 탐색기 창에서 프로젝트를 펼치고 데이터 세트를 클릭한 다음 데이터 세트를 선택합니다.

  3. 개요 > 테이블을 클릭한 다음 테이블을 선택합니다.

  4. 세부정보 창에서 복사를 클릭합니다.

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

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

SQL

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

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

    BigQuery로 이동

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

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

  3. 실행을 클릭합니다.

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
    
  3. 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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.
                .ThrowOnAnyError();
    
            // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 BigQuery Java API 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
  3. API

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

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

    Go

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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
    }
    

    Java

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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))

리전 간 테이블 복사

BigQuery 리전이나 멀티 리전에서 다른 리전으로 테이블, 테이블 스냅샷 또는 테이블 클론을 복사할 수 있습니다. 여기에는 고객 관리 Cloud KMS(CMEK)가 적용된 모든 테이블이 포함됩니다.

리전 간에 테이블을 복사하면 BigQuery 가격 책정에 따라 추가 데이터 전송 요금이 발생합니다. 리전 간 테이블 복사 작업이 완료되기 전에 취소하더라도 추가 요금이 청구됩니다.

리전 간에 테이블을 복사하려면 다음 옵션 중 하나를 선택합니다.

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. bq cp 명령어를 실행합니다.

  3.    bq cp \
       -f -n \
       SOURCE_PROJECT:SOURCE_DATASET.SOURCE_TABLE \
       DESTINATION_PROJECT:DESTINATION_DATASET.DESTINATION_TABLE
       

    다음을 바꿉니다.

    • SOURCE_PROJECT: 소스 프로젝트 ID. 소스 데이터 세트가 기본 프로젝트가 아닌 다른 프로젝트에 있으면 소스 데이터 세트 이름에 프로젝트 ID를 추가합니다.

    • DESTINATION_PROJECT: 대상 프로젝트 ID. 대상 데이터 세트가 기본 프로젝트가 아닌 다른 프로젝트에 있으면 대상 데이터 세트 이름에 프로젝트 ID를 추가합니다.

    • SOURCE_DATASET: 소스 데이터 세트의 이름

    • DESTINATION_DATASET: 대상 데이터 세트의 이름

    • SOURCE_TABLE: 복사할 테이블

    • DESTINATION_TABLE: 대상 데이터 세트의 테이블 이름

    다음 예시는 us 멀티 리전에서 eu 멀티 리전의 mydataset_eu.mytable2 테이블로 mydataset_us.mytable 테이블을 복사하는 명령어입니다. 두 데이터 세트 모두 기본 프로젝트에 있습니다.

    bq cp --sync=false mydataset_us.mytable mydataset_eu.mytable2
    

    리전 간에 테이블을 CMEK 지원 대상 데이터 세트로 복사하려면 테이블의 리전에서 키를 사용하여 테이블에서 CMEK를 사용 설정해야 합니다. 테이블의 CMEK는 대상 데이터 세트에서 사용 중인 CMEK와 동일하지 않아도 됩니다. 다음 예에서는 bq cp 명령어를 사용하여 CMEK 사용 설정 테이블을 대상 데이터 세트에 복사합니다.

    bq cp source-project-id:source-dataset-id.source-table-id destination-project-id:destination-dataset-id.destination-table-id
    

    반대로 CMEK가 사용 설정된 테이블을 리전 간에 대상 데이터 세트로 복사하려면 대상 데이터 세트의 리전에서 키를 사용하여 대상 데이터 세트에서 CMEK를 사용 설정하면 됩니다. 다음 예와 같이 bq cp 명령어에서 destination_kms_keys 플래그를 사용할 수도 있습니다.

    bq cp --destination_kms_key=projects/project_id/locations/eu/keyRings/eu_key/cryptoKeys/eu_region mydataset_us.mytable mydataset_eu.mytable2
    

    API

    API를 사용하여 리전 간에 테이블을 복사하려면 jobs.insert 메서드를 호출하고 테이블 copy 작업을 구성합니다.

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

    C#

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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.
                .ThrowOnAnyError();
    
            // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 BigQuery Java API 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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.")

제한사항

리전 간에 테이블을 복사하는 경우 다음과 같은 제한사항이 적용됩니다.

  • Google Cloud 콘솔 또는 TABLE COPY DDL 문을 사용하여 테이블을 복사할 수는 없습니다.
  • 소스 테이블에 정책 태그가 있으면 테이블을 복사할 수 없습니다.
  • 소스 테이블이 물리적으로 20TiB를 초과하는 경우 테이블을 복사할 수 없습니다. 소스 테이블의 물리적 크기는 테이블 정보 가져오기를 참조하세요. 또한 1TiB를 초과하는 소스 테이블을 리전 간에 복사하려면 여러 번 재시도해야 복사에 성공할 수 있습니다.
  • 테이블과 연결된 IAM 정책은 복사할 수 없습니다. 복사가 완료된 후 대상에 동일한 정책을 적용할 수 있습니다.
  • 복사 작업이 기존 테이블을 덮어쓰면 기존 테이블의 태그가 삭제됩니다.
  • 여러 소스 테이블을 단일 대상 테이블에 복사할 수 없습니다.
  • 추가 모드에서 테이블을 복사할 수 없습니다.
  • 시간 이동 정보는 대상 리전에 복사되지 않습니다.
  • 테이블 클론이나 스냅샷을 새 리전으로 복사하면 테이블의 전체 사본이 생성됩니다. 이 경우 추가 스토리지 비용이 발생합니다.

현재 할당량 사용량 보기

INFORMATION_SCHEMA 쿼리를 실행하여 지정된 기간 동안 실행된 작업에 대한 메타데이터를 확인하여 쿼리, 로드, 추출, 복사 작업의 현재 사용량을 볼 수 있습니다. 현재 사용량을 할당량 한도와 비교하여 특정 유형 작업의 할당량 사용량을 결정할 수 있습니다. 다음 예시 쿼리는 INFORMATION_SCHEMA.JOBS 뷰를 사용하여 프로젝트별로 쿼리, 로드, 추출, 복사 작업 수를 나열합니다.

SELECT
  sum(case  when job_type="QUERY" then 1 else 0 end) as QRY_CNT,
  sum(case  when job_type="LOAD" then 1 else 0 end) as LOAD_CNT,
  sum(case  when job_type="EXTRACT" then 1 else 0 end) as EXT_CNT,
  sum(case  when job_type="COPY" then 1 else 0 end) as CPY_CNT
FROM `region-REGION_NAME`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE date(creation_time)= CURRENT_DATE()

복사 작업의 할당량 한도를 보려면 할당량 및 한도 - 복사 작업을 참조하세요.

테이블 삭제

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

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

데이터 세트의 모든 테이블을 삭제하려면 데이터 세트를 삭제합니다.

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

테이블을 삭제하면 이 테이블과 연결된 권한도 삭제됩니다. 삭제된 테이블을 다시 만들 때는 이전에 연결된 모든 액세스 권한을 수동으로 다시 구성해야 합니다.

필요한 역할

테이블을 삭제하는 데 필요한 권한을 얻으려면 관리자에게 데이터 세트에 대한 데이터 편집자(roles/bigquery.dataEditor) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 테이블을 삭제하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

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

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

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

테이블 삭제

테이블을 삭제하는 방법:

콘솔

  1. 왼쪽 창에서 탐색기를 클릭합니다.

    탐색기 창의 강조 표시된 버튼

  2. 탐색기 창에서 프로젝트를 펼치고 데이터 세트를 클릭한 다음 데이터 세트를 선택합니다.

  3. 개요 > 테이블을 클릭한 다음 테이블을 선택합니다.

  4. 세부정보 창에서 삭제를 클릭합니다.

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

SQL

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

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

    BigQuery로 이동

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

    DROP TABLE mydataset.mytable;

  3. 실행을 클릭합니다.

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
    
  3. API

    tables.delete API 메서드를 호출하고 tableId 파라미터를 사용하여 삭제할 테이블을 지정합니다.

    C#

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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
    }
    

    Java

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

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    // 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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    
    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 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

    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

삭제된 테이블 복원

삭제된 테이블을 복원하거나 삭제 취소하는 방법을 알아보려면 삭제된 테이블 복원을 참고하세요.

테이블 보안

BigQuery에서 테이블에 대한 액세스를 제어하려면 IAM으로 리소스에 대한 액세스 제어를 참고하세요.

다음 단계