오늘의 인기 글
최근 글
최근 댓글
Today
Total
04-28 07:25
관리 메뉴

우노

[GCP] Bigquery 테이블 생성 with Python 본문

GCP/Bigquery

[GCP] Bigquery 테이블 생성 with Python

운호(Noah) 2024. 3. 21. 14:56

들어가기 앞서,

  • 해당 포스팅에선 Google Cloud의 BigQuery Python 클라이언트 라이브러리를 사용하여 BigQuery에 파티션된 테이블을 생성하는 코드에 대해서 다뤄보겠습니다.

예제 코드

# Google Cloud의 BigQuery 클라이언트 라이브러리를 가져옵니다.
from google.cloud import bigquery

# 사용할 BigQuery 프로젝트의 ID를 설정합니다.
project_id = "your_project_id"

# BigQuery 클라이언트 객체를 생성합니다.
bigquery_client = bigquery.Client(project=project_id)

# 생성할 BigQuery 테이블의 스키마를 정의합니다.
schema = [
    bigquery.SchemaField('category_l', 'STRING'),
    bigquery.SchemaField('category_m', 'STRING'),
    bigquery.SchemaField('category_s', 'STRING'),
    bigquery.SchemaField('company_name', 'STRING'),
    bigquery.SchemaField('date', 'DATE'),
    bigquery.SchemaField('hour', 'INTEGER'),
    bigquery.SchemaField('minute', 'INTEGER'),
    bigquery.SchemaField('usage', 'FLOAT'),
]

# 대상 데이터셋 ID와 테이블 ID를 지정합니다.
dataset_id = "your_dataset_id"
table_id = "your_table_id"

# 데이터셋 및 테이블 참조를 생성합니다.
table_ref = bigquery_client.dataset(dataset_id).table(table_id)

# 테이블 객체를 생성하고 스키마를 설정합니다.
table = bigquery.Table(table_ref, schema=schema)

# 테이블에 대한 시간 기반 파티션 설정을 추가합니다.
table.time_partitioning = bigquery.TimePartitioning(
    type_=bigquery.TimePartitioningType.DAY,  # 파티션 유형 설정 (일별)
    field='date',  # 파티션을 위한 컬럼 지정
    require_partition_filter=True  # 파티션 필터 필요 여부 설정
)

# 동일한 이름의 테이블이 존재하는 경우 삭제합니다 (선택적).
try:
    bigquery_client.delete_table(table)
except Exception as e:
    print(e)  # 에러 출력

# 테이블을 생성합니다.
create_table_result = bigquery_client.create_table(table)

# 생성 결과를 출력합니다.
print(f"Table {create_table_result.full_table_id} created.")

'GCP > Bigquery' 카테고리의 다른 글

[GCP] GCS → Bigquery with Python  (0) 2024.03.21
Comments