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.
Truy cập AWS Management Console

Đầ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:

Trong hộp thoại cấu hình Notebook
summit-fcj-datalake-notebook.ipynb bạn vừa lưu.
Môi trường Notebook sẽ được mở ra thành công.

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.”

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

Hệ thống thông báo Session đang phản hồi và sẵn sàng để chạy PySpark code.

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

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")

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()

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()))

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)

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)

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)

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()))

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()))

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')

Xem qua schema mới sau quá trình gộp nội dung.
joined_data.printSchema()

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'])

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)

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)

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')

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'])

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

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...).

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.
