/
Process the raw data

Process the raw data

Approach to Process and make the access Record queryable.

Introduction

In phase one, we have already sent access records to S3 in format of json with kinesis firehose delivery stream. Kinesis delivery stream creates partition of data on the basis of time in format of year, month and day, when the data has been received in s3. we want to process this data and make the processed data queryable. The data is growing with time, so we need to structure this big data in such a way that we can query it and process in adequate time.

What we actually need is ETL job which can extract the raw data from s3, process the data and load the processed data back in S3. From s3 we can query the data with Athena.

AWS Glue ETL Job

  1. Extract the raw data from source

  2. process the data

  3. load processed data to destination

Raw data means the data which we received directly from source, in our case it Synapse repository project. Synapse is sending access records to s3 with firehose kinesis delivery stream.

For each access record we need to calculate new fields like client, client_version etc from existing data according to business logic, Processing of data includes taking raw data and calculating new field data.

Now we want to keep processed data in glue table having a separate storage location of S3 which will be partitioned on basis of timestamp of access record as year, month and day. And want to execute Athena query on it. Data should be stored in Parquet format, Parquet is column based file format and fast file type to read.

The ETL job script would like as below:

""" This script executed by a Glue job. The job take the access record data from S3 and process it. Processed data stored in S3 in a parquet file partitioned by timestamp of record as year / month / day. """ import sys import datetime import re from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job from awsglue.dynamicframe import DynamicFrame # Get access record from source and create dynamic frame for futher processing def get_dynamic_frame(connection_type, file_format, source_path, glue_context): dynamic_frame = glue_context.create_dynamic_frame.from_options( format_options={"multiline": True}, connection_type=connection_type, format=file_format, connection_options={ "paths": [source_path], "recurse": True, "groupFiles": "inPartition", "groupSize": "1048576", }, transformation_ctx="dynamic_frame") return dynamic_frame def apply_mapping(dynamic_frame): mapped_dynamic_frame = ApplyMapping.apply( frame=dynamic_frame, mappings=[ ("payload.sessionId", "string", "SESSION_ID", "string"), ..... ], transformation_ctx="mapped_dynamic_frame") return mapped_dynamic_frame # process the access record def transform(dynamic_record): #transformation return dynamic_record def main(): # Get args and setup environment args = getResolvedOptions(sys.argv, ["JOB_NAME", "S3_SOURCE_PATH", "DATABASE_NAME", "TABLE_NAME"]) sc = SparkContext() glue_context = GlueContext(sc) spark = glue_context.spark_session job = Job(glue_context) job.init(args["JOB_NAME"], args) dynamic_frame = get_dynamic_frame("s3", "json", args["S3_SOURCE_PATH"], glue_context) mapped_dynamic_frame = apply_mapping(dynamic_frame) transformed_dynamic_frame = mapped_dynamic_frame.map(f=transform) # Write the processed access records to destination write_dynamic_frame = glue_context.write_dynamic_frame.from_catalog( frame=transformed_dynamic_frame, database=args["DATABASE_NAME"], table_name=args["TABLE_NAME"], additional_options={"partitionKeys": ["year", "month", "day"]}, transformation_ctx="write_dynamic_frame") job.commit() if __name__ == "__main__": main()

Challenges

  1. As we deploy every week new stack, ETL job should not reprocess the old or already processed data again.

2. How we will maintain the versioning of script of glue job, which means define infrastructure that should take the script and push it into s3 ( deployment process of script)

3. How to trigger the job e.g on demand, or on schedule time.

4. How to handle duplicate data.

Proposed solution :

  1. The ETL job will be static not created in every release.

  2. Create a GitHub project(Synapse-ETL-Jobs) for our etl job. Add GitHub action to create tag/release which will zip the source code and version it with every merge in develop branch, basically use GitHub as artifactory. In Synapse-Stack-Builder project create a new workflow, which will first download the python script form Syanpse-ETL-Jobs from latest tag and upload it to s3 from where glue job and take it for processing.Then create stack with cloud-formation template that will setup a glue job ,glue table, trigger and required resources.Build should include testing.

  3. It should be configurable parameter in stack builder. it should get triggered every hour.( In future we can find another way which can notify that new data is available for processing).

  4. One way to avoid duplicate data is we can used both source and destination as glue table for job and then use left join to identify the duplicate as below (for now we are not considering duplicate, in future we can look into it, if it will create problem)

stagingdatasource = gc.create_dynamic_frame.from_catalog( database="stagingdatabase", table_name="staging_source_table", transformation_ctx="stagingdatasource") targetdatasource = gc.create_dynamic_frame.from_catalog( database="targetdatabase", redshift_tmp_dir=args["TempDir"], table_name="target_table", transformation_ctx="targetdatasource") columnmapping = ApplyMapping.apply( frame=stagingdatasource, mappings=[("description", "string", "description", "string"), ("id", "int", "id", "int")], transformation_ctx="columnmapping") ta = columnmapping.toDF().alias('ta') tb = targetdatasource.toDF().alias('tb') left_join = ta\ .join(tb, ta.value == tb.value, how='left')\ .filter(col('tb.value').isNull())\ .select('ta.*') # Inspect left join # left_join.show() finaldf = DynamicFrame.fromDF(left_join, gc, "nested") gc.write_dynamic_frame.from_catalog( frame=finaldf, database="targetdatabase", redshift_tmp_dir=args["TempDir"], table_name="target_table")

Processed data destination

Processed data should be stored in S3 having portioned on access record timestamp. eg

dev.log.sagebase.org/processedAccessRecord/year/month/day.

Integrate with Redash

we need to integrate the processed access records to redash board which we used in our stack review meeting four audit purposes.

Alternative to access record processing :

While sending access record from synapse repository to firehose kinesis we can store both request url and processed url/ or only processed url. And kinesis should use dynamic partitioning on timestamp of access record to store data on s3. Now the data stored is already processed.Create a table from source S3 and Athena can query the data. ( not adequate because we might want to process data further, we need raw data in json format so it is available in readable format as well as processed data in parquet formate to query faster).

Related content

Processing Access Records using AWS (High Level Design)
Processing Access Records using AWS (High Level Design)
More like this
Monthly Project Statistics
Monthly Project Statistics
More like this
Iceberg Tables POC
Iceberg Tables POC
More like this