Data Transformation

Data Transformation

In this section, we will use an AWS Glue Studio Notebook to transform raw streaming data into a clean, enriched dataset. The notebook environment allows us to write PySpark code interactively, join data sources, and write transformed data back to S3 in an optimized format.

AWS Glue Studio Notebooks provide an interactive Apache Spark environment for developing and testing ETL scripts. The session runs on Glue’s serverless infrastructure — you do not need to manage any clusters.

Create AWS Glue Studio Notebook

  1. Access the AWS Management Console

    • Search for Glue
    • Select AWS Glue

    Data Transformation

  2. First, download the notebook file to your computer from First Cloud AI Journey. Use Ctrl + S (or Right-click -> Save As) to save the file as summit-fcj-datalake-notebook.ipynb.

    In the AWS Glue interface:

    • Select ETL jobs in the left menu
    • Under the Create job section, select Notebook

    Data Transformation

  3. In the Notebook configuration dialog

    • Select Upload Notebook
    • Click Choose file and select the summit-fcj-datalake-notebook.ipynb file you just downloaded.
    • For IAM role, select AWSGlueServiceRoleDefault
    • Click Create notebook

    Data Transformation

  4. The Notebook environment will open successfully.

    Data Transformation

  5. Click the Run/Play button on the first code cell (magic commands starting with %) to initialize the Interactive Session. Wait a few minutes until the output shows “Session … has been created.”

    Data Transformation

Run and Explain the Notebook Code

  1. Execute Code: Import Libraries

    Select the next code cell containing library imports and click Run.

    import sys
    from awsglue.transforms import *
    from awsglue.utils import getResolvedOptions
    from pyspark.context import SparkContext
    from awsglue.context import GlueContext
    from awsglue.job import Job
    import boto3
    import time
    

    Data Transformation

  2. The output will show that the session is successfully running and ready to accept PySpark code.

    Data Transformation

  3. Execute Code: Initialize Context

    Scroll down to the “Glue Dynamic Frames Basics” section. Run the cell to initialize GlueContext.

    glueContext = GlueContext(SparkContext.getOrCreate())
    spark = glueContext.spark_session
    

    Data Transformation

  4. Execute Code: Create Dynamic Frames

    Create dynamic frames from the tables in the Glue Catalog database (summitdb). Ensure the table_name matches your actual table name (e.g., raw2026 or raw).

    raw_data = glueContext.create_dynamic_frame.from_catalog(database = "summitdb", table_name = "raw")
    reference_data = glueContext.create_dynamic_frame.from_catalog(database = "summitdb", table_name = "reference_data")
    

    Data Transformation

  5. Execute Code: View Schema

    View the schema of the dynamic frames using the printSchema() method.

    raw_data.printSchema()
    reference_data.printSchema()
    

    Data Transformation

  6. Execute Code: Count Records

    Count the total number of records in your DataFrames.

    print('raw_data (Count) = ' + str(raw_data.count()))
    print('reference_data (Count) = ' + str(reference_data.count()))
    

    Data Transformation

  7. Execute Code: Display Sample Records

    Show the top 5 records from the DataFrames for preview.

    raw_data.toDF().show(5)
    reference_data.toDF().show(5)
    

    Data Transformation

  8. Execute Code: Explore Data using Spark SQL (Running)

    We will use Spark SQL to filter events with activity_type = Running.

    # Adding raw_data as a temporary table
    raw_data.toDF().createOrReplaceTempView("temp_raw_data")
    
    # Running the SQL statement
    runningDF = spark.sql("select * from temp_raw_data where activity_type = 'Running'")
    print("Running (count) : " + str(runningDF.count()))
    
    runningDF.show(5)
    

    Data Transformation

  9. Execute Code: Explore Data using Spark SQL (Working)

    Next, filter and count events where activity_type = Working.

    workingDF = spark.sql("select * from temp_raw_data where activity_type = 'Working'")
    print("Working (count) : " + str(workingDF.count()))
    
    workingDF.show(5)
    

    Data Transformation

  10. Execute Code: Glue Transforms Filtering

    Perform the same filter operation using Glue’s built-in Filter transform.

    def filter_function(dynamicRecord):
        if dynamicRecord['activity_type'] == 'Running':
            return True
        else:
            return False
    
    runningDF = Filter.apply(frame = raw_data, f = filter_function)
    print("Running (count) : " + str(runningDF.count()))
    

    Data Transformation

  11. Execute Code: Python Lambda Expressions

    Use an inline lambda expression to filter activity_type = Working.

    workingDF = Filter.apply(frame = raw_data, f = lambda x:x['activity_type']=='Working')
    print("Working (count) : " + str(workingDF.count()))
    

    Data Transformation

  12. Execute Code: Joining two Dataframes

    Join raw_data and reference_data on the track_id column using Join.apply().

    joined_data = Join.apply(raw_data, reference_data, 'track_id', 'track_id')
    

    Data Transformation

  13. Display the schema of the joined dynamic frame.

    joined_data.printSchema()
    

    Data Transformation

  14. Execute Code: Drop Partition Columns

    Data cleaning step using DropFields.apply() to remove automatically generated folder partition columns.

    joined_data_clean = DropFields.apply(frame = joined_data, paths = ['partition_0','partition_1','partition_2','partition_3'])
    

    Data Transformation

  15. View the schema and preview the top 5 records of the clean dataframe.

    joined_data_clean.printSchema()
    joined_data_clean.toDF().show(5)
    

    Data Transformation

  16. Execute Code: Writing data to S3

    Finally, write the transformed, clean data into your S3 bucket in column-based parquet format. Note: Please replace yourname-datalake-demo-bucket with your actual customized S3 bucket name.

    try:
        datasink = glueContext.write_dynamic_frame.from_options(
            frame = joined_data_clean, connection_type = "s3",
            connection_options = {"path": "s3://yourname-datalake-demo-bucket/data/processed-data/"},
            format = "parquet")
        print('Transformed data written to S3')
    except Exception as ex:
        print('Something went wrong')
        print(ex)
    

    Data Transformation

  17. Execute Code: Start Crawler via Boto3

    Use Python’s boto3 to trigger the SummitCrawler to catalog the new parquet data.

    glueclient = boto3.client('glue',region_name='ap-southeast-1')
    response = glueclient.start_crawler(Name='SummitCrawler')
    
    print('---')
    crawler_state = ''
    while (crawler_state != 'STOPPING'):
        response = glueclient.get_crawler(Name='SummitCrawler')
        crawler_state = str(response['Crawler']['State'])
        time.sleep(1)
    
    print('Crawler : Stopped')
    

    Data Transformation

  18. Check the tables in the summitdb database programmatically. A processed_data table should now be listed.

    print('** Summitdb has following tables**')
    response = glueclient.get_tables(DatabaseName='summitdb')
    for table in response['TableList']:
        print(table['Name'])
    

    Data Transformation

Verify Output on Amazon S3

  1. Go back to the AWS Management Console and search for S3.

    Data Transformation

  2. Click on Buckets in the left menu and open your data lake bucket (asg-datalake-demo-bucket).

    Data Transformation

  3. Navigate to data/processed-data/ folder. You will find multiple .parquet files which confirm that the transformation and writing job within the Notebook ran successfully.

    Data Transformation