Chuyển đổi dữ liệu

Chuyển đổi dữ liệu

Trong phần này, chúng ta sẽ sử dụng AWS Glue Studio Notebook để chuyển đổi dữ liệu streaming thô thành bộ dữ liệu sạch và được làm giàu. Môi trường notebook cho phép chúng ta viết code PySpark tương tác, join các nguồn dữ liệu và ghi dữ liệu đã chuyển đổi trở lại S3 ở định dạng tối ưu.

AWS Glue Studio Notebook cung cấp môi trường Apache Spark tương tác để phát triển và kiểm thử script ETL. Session chạy trên hạ tầng serverless của Glue — bạn không cần quản lý bất kỳ cluster nào.

Tạo AWS Glue Studio Notebook

  1. Truy cập AWS Management Console

    • Tìm Glue
    • Chọn AWS Glue

    Data Transformation

  2. Đầu tiên, hãy tải file notebook về máy tính của bạn từ First Cloud AI Journey. Sử dụng phím tắt Ctrl + S (hoặc Click chuột phải -> Save As) để lưu file với tên summit-fcj-datalake-notebook.ipynb.

    Trong giao diện AWS Glue:

    • Chọn ETL jobs ở menu bên trái
    • Dưới mục Create job, chọn Notebook

    Data Transformation

  3. Trong hộp thoại cấu hình Notebook

    • Chọn Upload Notebook
    • Chọn Choose file và tải lên file summit-fcj-datalake-notebook.ipynb bạn vừa lưu.
    • Tại phần IAM role, chọn AWSGlueServiceRoleDefault
    • Chọn Create notebook

    Data Transformation

  4. Môi trường Notebook sẽ được mở ra thành công.

    Data Transformation

  5. Bấm nút Run/Play ở dòng code đầu tiên (chứa các cài đặt cho %idle_timeout 2880...) để thiết lập một Interactive Session. Đợi một vài phút cho đến khi kết quả hiển thị “Session … has been created.”

    Data Transformation

Chạy và giải thích code trong Notebook

  1. Chạy Code: Import Libraries

    Chọn ô block code tiếp theo để tiến hành Import thư viện và bấm 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. Hệ thống thông báo Session đang phản hồi và sẵn sàng để chạy PySpark code.

    Data Transformation

  3. Chạy Code: Khởi tạo Context

    Kéo xuống mục “Glue Dynamic Frames Basics”. Chạy ô lệnh dưới để khởi tạo GlueContext.

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

    Data Transformation

  4. Chạy Code: Tạo Dynamic Frames

    Lấy thông tin từ các Data Catalog table (summitdb). Đảm bảo table_name đang trỏ đúng tới tên table của bạn (chẳng hạn raw2026 hay 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. Chạy Code: Xem Schema

    Hiển thị thông tin schema của cả 2 frame vừa lấy được thông qua printSchema().

    raw_data.printSchema()
    reference_data.printSchema()
    

    Data Transformation

  6. Chạy Code: Đếm lượng dữ liệu

    Tiến hành đếm xem có bao nhiêu record cho mỗi data frame.

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

    Data Transformation

  7. Chạy Code: Lấy mẫu dữ liệu

    Hiển thị nhanh 5 record mẫu đầu tiên ở cả 2 frame ra bảng console.

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

    Data Transformation

  8. Chạy Code: Sử dụng Spark SQL (Running)

    Dùng Spark SQL để tiến hành query, chọn những dữ kiện mà 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. Chạy Code: Sử dụng Spark SQL (Working)

    Tương tự như trên, tìm tất cả dữ kiện mà 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. Chạy Code: Tạo Glue Transforms Filtering

    Sử dụng Glue Transform API tích hợp sẵn thay thế cho SQL để thực hiện filter tương tự.

    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. Chạy Code: Ứng dụng Python Lambda Expressions

    Cách này giúp chúng ta viết code filter một cách ngắn gọn hơn để lọc cho giá trị Working.

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

    Data Transformation

  12. Chạy Code: Join 2 Dataframes

    Gộp dòng dữ kiện lấy sensor từ AWS IoT và artist metadata thành một bộ bằng Join.apply(), với key gộp chung là track_id.

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

    Data Transformation

  13. Xem qua schema mới sau quá trình gộp nội dung.

    joined_data.printSchema()
    

    Data Transformation

  14. Chạy Code: Lọc bỏ các cột Data Partition thừa

    Trong quá trình Firehose đưa dữ liệu ra lưu trữ, Firehose đã đặt các file vào folder thư mục theo ngày giờ, dẫn tới việc tự động sinh ra các label cột từ partition_0 đến partition_3. Dùng hàm DropFields.apply() để loại bỏ.

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

    Data Transformation

  15. Schema và giá trị 5 cột record mẫu lúc này đã hoàn thiện sạch sẽ.

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

    Data Transformation

  16. Chạy Code: Đưa file data về lại S3

    Ghi dữ liệu mới đã được transform trở lại thành file dạng parquet nén và đẩy vào bucket AWS S3. Lưu ý: Xin vui lòng cập nhật lại field yourname-datalake-demo-bucket thành đúng tên bucket S3 Data Lake cá nhân của bạn.

    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. Chạy Code: Bật Crawler bằng Boto3 Crawler

    Chỉ định AWS chạy lại SummitCrawler một cách tự động thông qua Python boto3. Việc này giúp update danh mục file tĩnh bên trong S3 qua Glue Catalog.

    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. Xác minh tính khả dụng của table processed_data ngay trên script Python. Một bảng ghi mới bao gồm thông tin từ file parquet đã được liệt kê.

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

    Data Transformation

Kiểm tra đầu ra từ nguồn Amazon S3

  1. Truy cập AWS Management Console và Search S3.

    Data Transformation

  2. Click chọn Buckets từ thanh điều khiển bên trái, mở data lake bucket cá nhân của bạn (asg-datalake...).

    Data Transformation

  3. Di chuyển vào thư mục data/processed-data/. Bạn sẽ dễ dàng quan sát thấy những file .parquet được khởi tạo thành công bằng hệ thống mã lệnh.

    Data Transformation