데이터 탐색 및 추출

다단계 데이터 아키텍처는 데이터를 브론즈, 실버, 골드의 점진적으로 개선된 품질 등급으로 구성합니다. 이 아키텍처는 원시 데이터를 깨끗하고 안정적인 애셋으로 변환하는 구조화된 방법론을 제공합니다.

이 문서에서는 외부 소스 시스템에서 데이터를 가져오는 브론즈 등급을 만드는 방법을 보여줍니다. 이 등급은 단일 정보 소스를 제공하고, 완전한 데이터 계보를 보장하며, 파이프라인의 재처리를 지원합니다.

시작하기 전에

  1. 계정에 로그인합니다. Google Cloud 를 처음 사용하는 경우 Google Cloud, 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Compute Engine, BigQuery, and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Create a service account:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    3. Select your project.
    4. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    5. Click Create and continue.
    6. Grant the following roles to the service account: Storage Object Admin, Dataproc Worker.

      To grant a role, find the Select a role list, then select the role.

      To grant additional roles, click Add another role and add each additional role.

    7. Click Continue.
    8. Click Done to finish creating the service account.

  6. Google Cloud CLI를 설치합니다.

  7. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  8. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  10. Verify that billing is enabled for your Google Cloud project.

  11. Enable the Compute Engine, BigQuery, and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  12. Create a service account:

    1. Ensure that you have the Create Service Accounts IAM role (roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles.
    2. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    3. Select your project.
    4. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    5. Click Create and continue.
    6. Grant the following roles to the service account: Storage Object Admin, Dataproc Worker.

      To grant a role, find the Select a role list, then select the role.

      To grant additional roles, click Add another role and add each additional role.

    7. Click Continue.
    8. Click Done to finish creating the service account.

  13. Google Cloud CLI를 설치합니다.

  14. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  15. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init

Cloud Storage에 원시 데이터 가져오기

Cloud Storage의 초기 스토리지 레이어로 원시 데이터를 수집합니다. 데이터 수집을 시뮬레이션하려면 BigQuery에서 Cloud Storage 버킷으로 공개 데이터 세트를 내보냅니다. 이 프로세스는 원시 데이터 파일을 랜딩 영역으로 전송하는 외부 시스템을 모방합니다.

  1. 데이터 레이크 역할을 할 Cloud Storage 버킷을 만듭니다. 성능을 최적화하려면 Apache Spark용 관리형 서비스 클러스터와 동일한 리전에서 만듭니다.

    gsutil mb -l REGION gs://BUCKET_NAME/
    
  2. bigquery-public-data:samples.shakespeare 테이블을 CSV 형식으로 Cloud Storage 버킷으로 내보냅니다.

    bq extract \
        --destination_format CSV \
        "bigquery-public-data:samples.shakespeare" \
        "gs://BUCKET_NAME/raw/shakespeare/shakespeare.csv"
    

    이 명령어는 테이블의 콘텐츠를 지정된 Cloud Storage 경로에 쓰는 내보내기 작업을 시작합니다.

PySpark로 원시 데이터 읽기

Cloud Storage에 데이터를 가져온 후 Apache Spark용 관리형 서비스 클러스터에서 PySpark 작업을 사용하여 데이터를 읽고 탐색합니다. Apache Spark는 Cloud Storage 커넥터를 통해 Cloud Storage와 상호작용하므로 gs:// URI 스키마를 사용하여 데이터를 읽고 쓸 수 있습니다.

  1. 다음 PySpark 스크립트를 사용하여 SparkSession을 만들고 Cloud Storage 액세스를 위해 구성한 후 원시 CSV 파일을 DataFrame으로 읽습니다.

    from pyspark.sql import SparkSession
    
    # --- Configuration ---
    gcs_bucket = "BUCKET_NAME"
    raw_path = f"gs://{gcs_bucket}/raw/shakespeare/shakespeare.csv"
    # For local development only.
    service_account_key_path = "/path/to/your/service-account-key.json"
    
    # --- Spark Session Initialization ---
    spark = SparkSession.builder \
      .appName("DataprocETL-RawIngestion") \
      .config("spark.jars", "https://storage.googleapis.com/hadoop-lib/gcs/gcs-connector-hadoop3-latest.jar") \
      .getOrCreate()
    
    # --- Authentication for local development ---
    # This step is not necessary when running on a Dataproc cluster
    # with the service account attached to the cluster VMs.
    spark.conf.set("google.cloud.auth.service.account.json.keyfile", service_account_key_path)
    
    # --- Read Raw Data from Cloud Storage ---
    # Read the raw CSV data into a DataFrame.
    # inferSchema=True scans the data to determine column types.
    raw_df = spark.read.csv(raw_path, header=True, inferSchema=True)
    
    # --- Initial Exploration ---
    print("Raw data count:", raw_df.count())
    print("Schema:")
    raw_df.printSchema()
    print("Sample of raw data:")
    raw_df.show(10, truncate=False)
    
    # --- Stop Spark Session ---
    spark.stop()
    
  2. 스크립트를 Apache Spark용 관리형 서비스 작업으로 실행하여 원시 데이터를 수집하고 탐색합니다.

데이터 수집 패턴

브론즈 등급은 일괄 파일 업로드 외에도 다양한 수집 패턴을 지원할 수 있습니다. Apache Spark용 관리형 서비스는 다양한 수집 시나리오를 처리할 수 있는 다용도 엔진입니다.

스트리밍 수집

IoT 센서 데이터 또는 애플리케이션 로그와 같은 연속 데이터 소스의 경우 스트리밍 파이프라인을 사용합니다. Apache Spark용 관리형 서비스를 사용하여 Pub/Sub 또는 Apache Kafka와 같은 서비스의 대용량 스트림을 처리하고 브론즈 등급에 데이터를 가져올 수 있습니다.

데이터베이스 수집

데이터 레이크를 운영 데이터베이스와 동기화하려면 변경 데이터 캡처 (CDC)를 사용합니다. Apache Spark용 관리형 서비스 Spark 작업은 변경 이벤트를 수신하는 Pub/Sub 주제를 구독하고 스트림을 처리하며 Cloud Storage의 원시 데이터 스토어에 변경사항을 적용할 수 있습니다.

다음 단계