Explora y extrae datos

Una arquitectura de datos de varias etapas organiza los datos en niveles de calidad progresivamente refinados: bronce, plata y oro. Esta arquitectura proporciona una metodología estructurada para transformar los datos sin procesar en recursos limpios y confiables.

En este documento, se muestra cómo crear el nivel bronce, en el que se almacenan los datos de los sistemas fuente externos. Este nivel proporciona una única fuente de información, garantiza un linaje de datos completo y permite el reprocesamiento de canalizaciones.

Antes de comenzar

  1. Accede a tu cuenta de Google Cloud . Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  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. Instala Google Cloud CLI.

  7. Si usas un proveedor de identidad externo (IdP), primero debes acceder a la gcloud CLI con tu identidad federada.

  8. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    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. Instala Google Cloud CLI.

  14. Si usas un proveedor de identidad externo (IdP), primero debes acceder a la gcloud CLI con tu identidad federada.

  15. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    gcloud init

Cómo transferir datos sin procesar a Cloud Storage

Transfiere datos sin procesar a una capa de almacenamiento inicial en Cloud Storage. Para simular la transferencia de datos, exporta un conjunto de datos públicos de BigQuery a un bucket de Cloud Storage. Este proceso simula un sistema externo que entrega archivos de datos sin procesar a una zona de destino.

  1. Crea un bucket de Cloud Storage para que funcione como data lake. Crea la CA en la misma región que tu clúster del servicio administrado para Apache Spark para optimizar el rendimiento.

    gsutil mb -l REGION gs://BUCKET_NAME/
    
  2. Exporta la tabla bigquery-public-data:samples.shakespeare a tu bucket de Cloud Storage en formato CSV.

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

    Este comando inicia un trabajo de exportación que escribe el contenido de la tabla en la ruta de Cloud Storage especificada.

Cómo leer datos sin procesar con PySpark

Después de transferir los datos a Cloud Storage, usa un trabajo de PySpark en un clúster de Managed Service for Apache Spark para leerlos y explorarlos. Apache Spark interactúa con Cloud Storage a través del conector de Cloud Storage, que te permite usar el esquema de URI gs:// para leer y escribir datos.

  1. Usa la siguiente secuencia de comandos de PySpark para crear un objeto SparkSession, configurarlo para el acceso a Cloud Storage y leer el archivo CSV sin procesar en un 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. Ejecuta la secuencia de comandos como un trabajo de Managed Service for Apache Spark para ingerir y explorar los datos sin procesar.

Patrones de transferencia de datos

El nivel bronce puede admitir varios patrones de transferencia más allá de las cargas de archivos por lotes. El servicio administrado para Apache Spark es un motor versátil capaz de controlar diversos casos de uso de la transferencia de datos.

Transferencia de transmisión

Para las fuentes de datos continuos, como los datos de sensores de IoT o los registros de aplicaciones, usa una canalización de transmisión. Puedes usar Managed Service para Apache Spark para procesar flujos de gran volumen desde un servicio como Pub/Sub o Apache Kafka y transferir los datos al nivel bronce.

Transferencia de bases de datos

Para mantener el data lake sincronizado con las bases de datos operativas, usa la captura de datos modificados (CDC). Un trabajo de Spark de Managed Service for Apache Spark puede suscribirse a un tema de Pub/Sub que recibe eventos de cambio, procesar la transmisión y aplicar los cambios al almacén de datos sin procesar en Cloud Storage.

¿Qué sigue?