<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sanjay Jayakumar on Medium]]></title>
        <description><![CDATA[Stories by Sanjay Jayakumar on Medium]]></description>
        <link>https://medium.com/@sanjay28.js?source=rss-67c434b1b944------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9CBptlpYOZ4Wf2msrBqRSg@2x.jpeg</url>
            <title>Stories by Sanjay Jayakumar on Medium</title>
            <link>https://medium.com/@sanjay28.js?source=rss-67c434b1b944------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:02:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanjay28.js/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Near Real-Time Data Pipeline with Apache Iceberg and Apache Spark on AWS Cloud : Data…]]></title>
            <link>https://medium.com/@sanjay28.js/building-a-near-real-time-data-pipeline-with-apache-iceberg-and-apache-spark-on-aws-cloud-data-4e11df805e3d?source=rss-67c434b1b944------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e11df805e3d</guid>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <dc:creator><![CDATA[Sanjay Jayakumar]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 17:29:52 GMT</pubDate>
            <atom:updated>2025-04-29T18:01:45.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Near Real-Time Data Pipeline with Apache Iceberg and Apache Spark on AWS Cloud : Data Lakehouse</h3><p>I’m excited to share that I’ve been selected as an <strong>AWS Community Builder</strong>! This is an incredible opportunity, and I’m truly honored to be part of such an inspiring and supportive community.</p><p>For more details : <a href="https://aws.amazon.com/developer/community/community-builders/">https://aws.amazon.com/developer/community/community-builders/</a></p><p>As part of this program, I’m thrilled to publish my <strong>first article</strong> as an AWS Community Builder 🎉🎉— sharing hands-on insights and learnings</p><p>In this ETL project, our main goal is to build a <strong>Data Lakehouse</strong> solution in the AWS cloud, leveraging <strong>Apache Iceberg</strong>. It’s going to be an exciting journey, so let’s dive in!</p><h3><strong>Project Description</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jNkc9w5lEdbtqIM7KBbfg.png" /><figcaption>ETL Architecture</figcaption></figure><p>This ETL project is based on <strong>near-real-time processing</strong>.</p><p>A <strong>GPS data producer</strong>, hosted on an EC2 instance, simulates real-time GPS data as synthetic input for the pipeline.</p><p><strong>Data Ingestion &amp; Delivery</strong></p><ul><li><strong>Amazon Kinesis Data Streams</strong> acts as the <strong>ingestion layer</strong>, efficiently handling high-throughput streaming data from the GPS data producer.</li><li><strong>Amazon Kinesis Data Firehose</strong> acts as a consumer of the Kinesis stream. It <strong>batches and delivers</strong> the streaming data to an <strong>S3 Data Lake</strong> in <strong>JSONL format</strong>, based on the configured buffer size and time interval.</li></ul><blockquote>🔁 At this point, the data is stored in its <strong>raw form</strong> in S3 — preserving the native JSON structure received from Kinesis.</blockquote><p><strong>Event-Driven Processing</strong></p><ul><li>An <strong>S3 Event Notification</strong> is configured on the data lake bucket using a <strong>resource-based policy</strong> (S3 <strong>prefix filtering</strong>).</li><li>These notifications (of type s3:ObjectCreated:*) are published to an <strong>Amazon SQS queue</strong>, which stores the event metadata.</li></ul><p><strong>ETL and Lakehouse Integration</strong></p><ul><li>An <strong>ETL server</strong>, running on EC2, continuously polls the SQS queue for new messages in batches.</li></ul><p>For each batch, it:</p><ol><li><strong>Extracts</strong> the corresponding (incremental extraction) raw data from the S3 Data Lake.</li><li><strong>Appends</strong> it to the <strong>Data Lakehouse</strong>, which is built using <strong>Apache Iceberg</strong> — an open table format for large-scale analytics.</li></ol><p>Since the GPS data producer generates <strong>append-only data</strong>, the ETL logic is implemented for <strong>append mode</strong> only — ensuring high performance and simplicity in pipeline design.</p><blockquote>🗂️ The <strong>AWS Glue Data Catalog</strong> serves as the <strong>centralized metadata repository</strong> for the Apache Iceberg tables, enabling seamless querying and schema evolution.</blockquote><h3>Step-by-Step Implementation to Enabling The ETL project 🚀</h3><h3><strong>1. Set Up the Local Environment</strong></h3><ul><li>Clone the Git Repository</li></ul><pre>git clone https://github.com/Sanjay-dev-ds/streaming-data-pipeline-with-iceberg-and-spark.git</pre><ul><li>Configure the AWS CLI</li></ul><p>Before proceeding, ensure the AWS CLI is installed and configured with the necessary credentials and default region. You can configure it using the following command:</p><p>Navigate to the AWS config directory:</p><pre>cd ~/.aws</pre><p>Open the credentials file (or create it if it doesn&#39;t exist):</p><pre>vi credentials</pre><p>Add your profile something like this:</p><pre>[sanjay]<br>aws_access_key_id = YOUR_ACCESS_KEY<br>aws_secret_access_key = YOUR_SECRET_KEY</pre><pre>export AWS_PROFILE=sanjay</pre><p>verify the configuration</p><p>Check that your credentials are working:</p><pre>aws sts get-caller-identity</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*qr3v6vcgyusZt3azv1TJEg.png" /><figcaption>AWS Configuration</figcaption></figure><h3><strong>2. Create ETL Cloud Infrastructure</strong></h3><p>What is Terraform?</p><blockquote>- Terraform is an <strong>Infrastructure as Code (IaC)</strong> tool that allows us to <strong>build, change, and version</strong> infrastructure of cloud resources</blockquote><blockquote>- Terraform is <strong>platform agnostic</strong>. You can use it with any cloud services provider</blockquote><ul><li>Navigate to the infrastructure folder from the root:</li></ul><pre>cd infrastructure/</pre><p>Update the following values in <strong>Terraform configuration file</strong>:</p><ul><li>Update VPC config according your Default VPC</li></ul><pre>vpc_security_group_ids = [&quot;sg-XXXXXXXXX&quot;]<br>subnet_id              = &quot;subnet-XXXXXXX&quot;<br></pre><ul><li>Update key name</li></ul><pre>key_name = &quot;XXXXXX&quot;</pre><p><strong>To connect to EC2 instance, you need to create an AWS key pair (</strong><strong>.pem file). Follow these steps:</strong></p><ol><li>Go to the <strong>EC2 Dashboard</strong> in the AWS Console.</li><li>Navigate to <strong>Key Pairs</strong> → click <strong>Create Key Pair</strong>.</li><li>Enter a key name (e.g., my-ec2-key) and choose <strong>.pem</strong> as the file format.</li><li>Download the .pem file and store it securely on your machine.</li><li>update your Terraform configuration file with the key name</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*fOyY7Hn2A0wGh5FoF6moZg.png" /></figure><p><strong>Terraform Commands: (Follow the order)</strong></p><ol><li>terraform init - Initialize the working directory and download provider plugins.</li><li>terraform validate - Validate your configuration files.</li><li>terraform plan - Generate and preview the execution plan.</li><li>terraform apply - Apply the execution plan and provision resources.</li><li>terraform destroy - Tear down the infrastructure created by Terraform. <em>(Do not apply now, Apply it after completion </em>❗<em>)</em></li></ol><p>After running terraform apply, Terraform will prompt you to confirm the action.</p><p>Type yes to proceed and create the infrastructure on AWS. Once the deployment is successful, you’ll see a message like this:</p><pre>Apply complete! Resources: 17 added, 0 changed, 0 destroyed.</pre><p>Now All the cloud resources are created!</p><h3>3. Activation of Source System</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*iU7yfOGfqvbC8e21OymG-Q.png" /><figcaption>Producer</figcaption></figure><p>A data producer hosted on an EC2 instance pushes real-time GPS tracking data into a Kinesis Data Stream, which is configured in <strong>on-demand mode</strong> to automatically scale based on throughput.</p><p>Once your EC2 instance is created from above step, you can log in using the public IP address and the key pair you created earlier.</p><p>Note: Wait for 5 minutes after the infrastructure is created to allow the environment to initialize</p><p>In my case <em>ip-address</em>: 54–166–230–120</p><pre><br>ssh -i &quot;sanjay-2025.pem&quot; ubuntu@ec2-54-166-230-120.compute-1.amazonaws.com</pre><p>clone the git repository (if not found in server)</p><pre>git clone https://github.com/Sanjay-dev-ds/streaming-data-pipeline-with-iceberg-and-spark.git</pre><p>Activate the Python Virtual Environment using below command</p><p>source /home/ubuntu/etl_server_venv/bin/activate</p><p>Now, let’s navigate to the <strong>producer</strong> folder and activate the source system. This component simulates real-time GPS data and pushes it to the <strong>Kinesis Data Stream</strong>.</p><p>Run the following command:</p><p>bash start-producer.sh</p><p>After running the script, you should start seeing log outputs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaDIxWootEuY-edMYpOCmA.png" /><figcaption>output of producer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pis1PKJqQsC5T4j_7GvfCQ.png" /><figcaption>Kinesis Stream Monitoring</figcaption></figure><p>Now Let’s have a look on Script,</p><p>The following code block is used to generate GPS attributes, including attributes such as<em> vehicle_id, latitude, longitude, speed, direction, and timestamp</em>. It leverages the Faker and random modules to generate and simulate real-time GPS data.</p><pre>def generate_gps_data():<br>    &quot;&quot;&quot;Generates real-time GPS tracking data with additional attributes.&quot;&quot;&quot;<br><br>    vehicle_id = VehicleManager.get_random_vehicle()<br>    latitude = round(random.uniform(-90, 90), 6)<br>    longitude = round(random.uniform(-180, 180), 6)<br>    speed = round(random.uniform(0, 120), 2)<br>    direction = random.choice([&quot;N&quot;, &quot;S&quot;, &quot;E&quot;, &quot;W&quot;, &quot;NE&quot;, &quot;NW&quot;, &quot;SE&quot;, &quot;SW&quot;])<br>    timestamp = time.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br><br>    # Additional attributes<br>    is_ev = random.choice([True, False])<br>    fuel_level = None if is_ev else round(random.uniform(5, 100), 1)<br>    battery_level = round(random.uniform(10, 100), 1)  # If electric vehicle<br>    seat_belt_status = random.choice([&quot;Fastened&quot;, &quot;Unfastened&quot;])<br>    collision_detected = random.choice([True, False, False, False,False,False])<br>    sudden_braking = random.choice([True, False, False,False])<br><br>    gps_data = {<br>        &quot;vehicle_id&quot;: vehicle_id,<br>        &quot;latitude&quot;: latitude,<br>        &quot;longitude&quot;: longitude,<br>        &quot;speed_kmh&quot;: speed,<br>        &quot;direction&quot;: direction,<br>        &quot;fuel_level&quot;: fuel_level,<br>        &quot;battery_level&quot;: battery_level,<br>        &quot;seat_belt_status&quot;: seat_belt_status,<br>        &quot;collision_detected&quot;: collision_detected,<br>        &quot;sudden_braking&quot;: sudden_braking,<br>        &quot;timestamp&quot;: timestamp<br>    }<br><br>    return gps_data</pre><p>The <strong><em>VehicleManager </em></strong>class is designed to manage a set of vehicle IDs generated by Faker and provide a method to randomly select one.</p><pre>class VehicleManager:<br>    vehicles = [Faker().uuid4()[:8] for _ in range(20)]<br><br>    @staticmethod<br>    def get_random_vehicle():<br>        &quot;&quot;&quot;Returns a random vehicle ID&quot;&quot;&quot;<br>        return random.choice(VehicleManager.vehicles)</pre><p>Below Function push_to_kinesis, <strong>pushes real-time data</strong> into an <strong>AWS Kinesis Data Stream</strong> using the AWS SDK’s put_record() method.</p><pre>def push_to_kinesis(self, data):<br>        &quot;&quot;&quot;Pushes GPS data to AWS Kinesis.&quot;&quot;&quot;<br>        try:<br>            response = self.kinesis_client.put_record(<br>                StreamName=self.stream_name,<br>                Data=json.dumps(data),<br>                PartitionKey=data[&quot;vehicle_id&quot;]<br>            )<br>            logging.info(f&quot;Pushed to Kinesis: {data} | Response: {response[&#39;ResponseMetadata&#39;][&#39;HTTPStatusCode&#39;]}&quot;)<br>        except Exception as e:<br>            logging.error(f&quot;Failed to push data to Kinesis: {str(e)}&quot;)</pre><p>Here’s how it works:</p><ul><li>Each data point is sent<strong> as a record</strong> (single)to the Kinesis stream.</li><li>The script uses &quot;vehicle_id&quot; as the <strong>partition key</strong>. (High Cardinality)</li></ul><h4>🚗 Why Partition Keys Matter</h4><ul><li><strong>Partition keys</strong> help Kinesis <strong>distribute data evenly</strong> across multiple shards.</li><li>This improves scalability and performance by balancing the load.</li></ul><blockquote>⚠️ <strong>Important:</strong> If all records have the same partition key, they’ll be routed to the <strong>same shard</strong>, regardless of how many shards exist. This can cause a bottleneck.</blockquote><p>If too many records are sent to a single shard too quickly, you may encounter a <strong><em>ProvisionedThroughputExceededException</em></strong></p><p>📡 This simulation acts as the real-time data source for our entire ETL pipeline.</p><h3>4. Ingestion into Data Lake</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ZZTmMdiZ5Rbzj1E3Bk3YmQ.png" /><figcaption>Ingestion Flow</figcaption></figure><p>The <strong>Kinesis Data Stream</strong> collects and temporarily stores incoming GPS records, acting as a <strong>buffer</strong> for downstream processing.</p><p>Next, <strong>Amazon Kinesis Data Firehose</strong> is configured to <strong>read directly from the stream</strong>. Here’s how it configured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuZWt1I8PIEN45RthTPAYA.png" /><figcaption>Firehose Configurations</figcaption></figure><ul><li>Firehose <strong>buffers incoming data</strong> for up to <strong>120 seconds</strong> or until <strong>5 MB</strong> of data is accumulated — whichever comes first.</li><li>It then <strong>appends a newline delimiter</strong> to each record, processes the data into a <strong>newline-delimited JSONL file, </strong>and <strong>delivers it to an S3 bucket</strong> under the raw_batch_folder prefix.</li></ul><p><strong>JSONL :</strong></p><ul><li>Each line is a separate, valid JSON object.</li><li>Also known as NDJSON (Newline Delimited JSON).</li><li>Ideal for streaming, logging, or big data processing</li><li>Easier to append and process line-by-line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsiAubsYKck2fAC4e97niQ.png" /><figcaption>One Data Batch in Data Lake</figcaption></figure><blockquote><em>📂 The data stored in the </em><strong><em>S3 Data Lake</em></strong><em> is in its </em><strong><em>native format (JSON)</em></strong><em>, ready for further processing.</em></blockquote><h4>🔐 IAM Role and Permissions</h4><p>To perform read/write operations between <strong>Kinesis</strong> and <strong>S3</strong>, Firehose assumes an <strong>IAM role</strong> with the following AWS-managed policies attached:</p><ul><li>arn:aws:iam::aws:policy/AmazonS3FullAccess</li><li>arn:aws:iam::aws:policy/AmazonKinesisFullAccess</li></ul><p>These permissions allow Firehose to <strong>consume data from the stream</strong> and <strong>deliver it to S3</strong> securely.</p><h3>5. Data Loading into Data Lakehouse</h3><p>This is the most important step in our ETL pipeline</p><p>A <strong>Data Lakehouse</strong> is a unified data platform that combines the <strong>flexibility of data lakes</strong> with the <strong>performance and structure of data warehouses</strong>. It allows organizations to store data in open formats while enabling ACID transactions, schema evolution, and high-performance analytics.</p><p>In our ETL project, we’ve utilized <strong>Apache Iceberg</strong> as the core open table format to <strong>build a scalable Data Lakehouse solution</strong> on AWS.</p><p>So, let’s continue on the project…</p><p>Once a JSON file is delivered to the <strong>S3 bucket</strong> (under a specific prefix), an <strong>S3 Event Notification</strong> is triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bu48-ycliW4MvRhT3rwY7g.png" /><figcaption>Event Notification</figcaption></figure><ul><li>The bucket is configured to <strong>publish </strong><strong>s3:ObjectCreated:* events</strong> to an <strong>Amazon SQS queue</strong>. (<em>Prefix is raw_batch_folder and suffix is .json</em>)</li><li>This allows us to capture every new object (file) created in the specified path.</li></ul><p>The following image shows the number of available messages in the queue :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*853MAMLl8oGHDxWOgE5dvg.png" /><figcaption>SQS Queue</figcaption></figure><p><strong>⚙️ Spark ETL Server: Listening for Events</strong></p><p>A <strong>Spark-based ETL server</strong>, deployed on an <strong>EC2 instance</strong>, is configured to:</p><ul><li><strong>Continuously poll</strong> the SQS queue</li><li>Always Wait for up to <strong>10 seconds</strong> after a poll</li><li>Receive up to <strong>10 messages at a time</strong></li></ul><p>Each message contains information about the newly created file(s) in S3.</p><p>If there are any messages, it <strong>processes</strong> them using PySpark then <strong>commits</strong> (deletes) the messages from the queue.</p><pre>poller = Poller(sqs_url)<br><br><br>    spark = create_spark_session(catalog_name=catalog_name, namespace=namespace,<br>                                 s3_bucket_arn=s3_bucket_arn)<br><br>    while True:<br>        messages = poller.get_messages(10)<br><br>        if messages:<br>            process_message(messages,<br>                            spark,<br>                            catalog_name,<br>                            namespace,<br>                            table_name,<br>                            partition_cols,<br>                            sql_query,<br>                            compression<br>                            )<br>            poller.commit()<br><br>        logging.info(f&quot;Waiting 10 seconds before next poll&quot;)<br>        time.sleep(10)</pre><p>The create_spark_session function <strong>sets up and returns a Spark session</strong> configured to work with <strong>Apache Iceberg</strong> tables stored in <strong>AWS S3</strong> and cataloged in <strong>AWS Glue</strong>. It first builds a Spark session with important dependencies. It then configures Spark to use Iceberg’s SparkCatalog for catalog management, specifying AWS Glue as the catalog type, the S3 bucket as the warehouse location, and the AWS region</p><p><strong>In Depth into SQS Polling</strong></p><p>We created a Poller class with get_messages and commit functions, which are used to fetch new messages from the SQS queue and delete them after they are processed.</p><p>get_messages</p><ul><li>Polls up to batch_size messages from the SQS queue.</li><li>Waits up to <strong>20 seconds</strong> if there are no immediate messages.</li><li>Adds fetched messages to a list for later deletion.(self.messages_to_delete = [])</li></ul><p>commit():</p><ul><li>Deletes all the messages that were fetched earlier.</li><li>Clears the delete list after deleting.</li></ul><pre>class Poller:<br>    def __init__(self, queue_url):<br>        self.queue_url = queue_url<br>        self.sqs_client = boto3.client(&#39;sqs&#39;, region_name=&#39;us-east-1&#39;)<br>        self.messages_to_delete = []<br><br>    def get_messages(self, batch_size):<br>        logging.info(&quot;Polling messages from SQS queue&quot;)<br>        # if there is no messages it will wait for 20 seconds<br><br>        response = self.sqs_client.receive_message(<br>            QueueUrl=self.queue_url,<br>            MaxNumberOfMessages=batch_size,<br>            WaitTimeSeconds=20<br>        )<br><br>        if &#39;Messages&#39; in response:<br>            messages = response[&#39;Messages&#39;]<br>            for message in messages:<br>                self.messages_to_delete.append({<br>                    &#39;ReceiptHandle&#39;: message[&#39;ReceiptHandle&#39;],<br>                    &#39;Body&#39;: message[&#39;Body&#39;]<br>                })<br>            logging.info(f&quot;Retrieved {len(messages)} messages from the queue.&quot;)<br>            return messages<br>        else:<br>            logging.info(&quot;No messages retrieved from the queue.&quot;)<br>            return []<br><br>    def commit(self):<br>        for message in self.messages_to_delete:<br>            logging.info(f&quot;Deleting message: {message[&#39;Body&#39;]}&quot;)<br>            self.sqs_client.delete_message(<br>                QueueUrl=self.queue_url,<br>                ReceiptHandle=message[&#39;ReceiptHandle&#39;]<br>            )<br>        logging.info(f&quot;Deleted {len(self.messages_to_delete)} messages from the queue.&quot;)<br>        self.messages_to_delete = []</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GPBYhSKCXoOvzl3T-_v5A.png" /><figcaption>SQS Queue</figcaption></figure><p>The above image shows the ‘Messages Available’ count, which indicates the number of messages currently in the queue, while the ‘Messages in Flight’ count represents the number of messages being processed by the ETL server.<br> Once the S3 file is successfully loaded into the Data Lakehouse, the commit() function is called to delete the corresponding message from the SQS queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OclCQXY0u1gGkwz5fM4sQQ.png" /><figcaption>SQS Commit Logs</figcaption></figure><p><strong>🧠 Batch Processing with PySpark</strong></p><p>Based on the batch of received messages, the server build the full S3 path for files, All file paths are collected into a list called batch_files</p><p>Finally, if there are any files, it <strong>reads them using PySpark</strong> as a Spark DataFrame for further processing.</p><pre>if batch_files:<br>    multiline_df = spark.read.option(&quot;multiline&quot;, &quot;false&quot;).json(batch_files)</pre><p>The load_data_to_iceberg function is responsible for loading a Spark DataFrame into an Iceberg table. It first creates a temporary view from the input DataFrame and transforms to add <em>input_file name, processed timestamp and date</em> using PySpark SQL</p><p>It then configures the DataFrame writer to use<strong> Iceberg format with Parquet</strong> as the file format and &quot;<strong>copy-on-write</strong>&quot; mode for deletes, updates, and merges.</p><p>It also sets the Parquet compression codec (defaulting to Snappy).</p><p>The function checks if the target Iceberg table already exists: if it does, it <strong>appends the new data</strong>; if not, it creates a new table by overwriting.</p><h4>❄️ What is Apache Iceberg?</h4><p><strong>Apache Iceberg</strong> is an open-source table format designed for <strong>large analytic datasets</strong>, originally created by Netflix.</p><p>Iceberg allows you to <strong>treat files in cloud storage as tables</strong>, enabling you to perform <strong>SQL queries, inserts, updates, and deletes</strong> — just like you would in a traditional database.</p><p><strong>Key features of Iceberg include:</strong></p><p>✅ <strong>Engine Agnostic</strong> — Works seamlessly with different processing engines like Spark, Flink, Trino, and more.</p><p>✅ <strong>ACID Compliance</strong> — Ensures reliable transactions with support for atomic operations.</p><p>✅ <strong>Schema Evolution</strong> — Easily add, drop, or rename columns without breaking existing queries.</p><p>✅ <strong>Hidden Partitioning</strong> — Simplifies partition management without manual intervention.</p><p>✅ <strong>Time Travel</strong> — Query historical versions of your data at specific points in time.</p><p>✅ <strong>Data Compaction</strong> — Optimize data layout for faster queries and reduced storage costs.</p><p>🚀Now, let’s start the Spark server to load data into the data lake house.<br>Run the following command:</p><p>bash start-etl-server.sh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*veeDsXoh5XmjC8GPTEyYkQ.png" /></figure><p>You will see output logs indicating that the Spark session is being initialized. Once ready, the server will begin polling messages from the SQS queue, fetch the corresponding JSON files from S3, load them into Spark DataFrames, and finally write the data into the Iceberg table.</p><p>After the data has been successfully loaded into the lake house, you can navigate to the specified S3 location, where you’ll find both the data and metadata directories created by Iceberg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ZcnxWX3CSas4T0vgxZSZYQ.png" /></figure><p><strong>Data Directory</strong> (data/)<br> This folder stores the actual <strong>Parquet</strong> files that contain your table&#39;s <strong>real GPS data</strong>. These are the files that get <strong>read during queries</strong>.</p><p><strong>Metadata Directory</strong> (metadata/)<br>This folder stores the <strong>table&#39;s metadata files</strong></p><h3>7. Consumption Layer</h3><h4>1. Athena</h4><p>You can use Athena to perform read operation ICEBERG table that we’ve created, You can use SQL to run ad-hoc queries and get results in seconds.</p><pre>SELECT *<br>FROM &quot;gps_glue_catalog_v2&quot;.&quot;gps_tracking_table&quot;<br>LIMIT 10;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_OdSXXMEYUw0c_hCFemEA.png" /><figcaption>Query Output</figcaption></figure><p>You can see the total amount data scanned by the query</p><h4>2. Snowflake</h4><p><strong>Snowflake</strong> supports reading and querying <strong>Apache Iceberg tables</strong> where the actual data resides in <strong>external cloud storage</strong>, such as <strong>Amazon S3</strong>. These are referred to as <strong>Unmanaged Iceberg Tables</strong></p><p>This improve data interoperability and performance for integrated data lakes.</p><p>To proceed with this step, you’ll need access to a <strong>Snowflake account</strong>. Once you’re logged in:</p><ol><li>Open a <strong>new SQL worksheet</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIB9xC55ThK699dQSfaxqA.png" /></figure><p>Run below command to create DB and Warehouse for Compute :</p><pre>USE ROLE ACCOUNTADMIN;<br><br>CREATE OR REPLACE DATABASE GPS_DB;<br><br>CREATE OR REPLACE WAREHOUSE COMPUTE_WH<br>  WITH WAREHOUSE_SIZE = &#39;XSMALL&#39;<br>  INITIALLY_SUSPENDED = TRUE;</pre><p><strong>Create an External Volume in Snowflake</strong></p><p>An <strong>External Volume</strong> is a <strong>named, account-level object</strong> in Snowflake that enables integration with <strong>external cloud storage</strong> — specifically for use with <strong>Iceberg tables</strong>.</p><p>To create an external volume, you need to provide:</p><ul><li>The <strong>S3 storage location (URL)</strong> where your Iceberg table data resides.</li><li>An <strong>AWS IAM Role ARN</strong> that grants Snowflake the required permissions to access the S3 bucket.</li></ul><pre>CREATE OR REPLACE EXTERNAL VOLUME S3_EXT_VOL<br> STORAGE_LOCATIONS =<br> (<br> (<br> NAME = &#39;s3-external-volume&#39;<br> STORAGE_PROVIDER = &#39;S3&#39;<br> STORAGE_BASE_URL = &#39;s3://gps-tracking-data-bucket-02122025-sanjay-de/warehouse/&#39;<br> STORAGE_AWS_ROLE_ARN = &#39;arn:aws:iam::XXXXXXXXX:role/spark-processing-role&#39;<br>)<br> );</pre><p>After creating the EXTERNAL VOLUME, run the following command in Snowflake to retrieve the <strong>STORAGE_AWS_IAM_USER_ARN</strong>:</p><pre>DESC EXTERNAL VOLUME S3_EXT_VOL;</pre><p>This ARN represents the <strong>Snowflake IAM user</strong> that will access your S3 bucket.</p><p>Next, update the <strong>trust relationship</strong> in the AWS IAM role (the one you assigned earlier) to <strong>allow this Snowflake IAM user to assume the role</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*TxYz7tNIn_WMcDxBdFXbkg.png" /></figure><p><strong>Configure a catalog integration for AWS Glue</strong></p><p>Next, we’ll set up a <strong>catalog integration</strong> with the <strong>AWS Glue Data Catalog</strong>, allowing Snowflake to access Iceberg table metadata stored in Glue.</p><p>Use the following SQL to create the integration:</p><pre>CREATE or REPLACE CATALOG INTEGRATION GLUE_CATELOG_INTEGRATION<br>  CATALOG_SOURCE=GLUE<br>  CATALOG_NAMESPACE=&#39;gps_glue_catalog_v2&#39;<br>  TABLE_FORMAT=ICEBERG<br>  GLUE_AWS_ROLE_ARN=&#39;arn:aws:iam::XXXXXXXXX:role/spark-processing-role&#39;<br>  GLUE_CATALOG_ID=&#39;XXXXXXXXX&#39;<br>  GLUE_REGION = &#39;us-east-1&#39;<br>  REFRESH_INTERVAL_SECONDS = 30<br>  ENABLED=TRUE; <br></pre><p>Then, describe the integration to verify the configuration:</p><pre>DESC CATALOG INTEGRATION GLUE_CATALOG_INTEGRATION;</pre><p>We get same <strong>Snowflake IAM user as earlier</strong></p><p>Since this integration also uses the <strong>same IAM role</strong> (spark-processing-role) as before, <strong>you do not need to update the trust policy again</strong>.</p><p>Final Step, we can create an <strong>Iceberg table</strong> by referencing both the <strong>Glue Catalog integration</strong> and the <strong>External Volume</strong> we configured earlier. This allows Snowflake to access table metadata from Glue while reading the actual data directly from S3.</p><pre>CREATE OR REPLACE ICEBERG TABLE GPS_TRACKING_TABLE<br>  EXTERNAL_VOLUME=&#39;S3_EXT_VOL&#39;<br>  CATALOG=&#39;GLUE_CATELOG_INTEGRATION&#39;<br>  CATALOG_TABLE_NAME=&#39;gps_tracking_table&#39;<br>  ;<br></pre><p>Let’s read the GPS data in Iceberg format from S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQMSbinPEOpIXqxT1FEVBQ.png" /></figure><p>From this, we understand that Apache Iceberg is compatible with multiple query engines</p><h3>8. Conclusion</h3><p>So, we’ve come to the end of this project. This end-to-end implementation demonstrates how to build a <strong>data lake house from scratch using AWS cloud services</strong>, leveraging a wide range of tools and integrations.</p><p>From simulating near real-time GPS data, ingesting with <strong>Kinesis</strong>, buffering and delivering with <strong>Firehose</strong>, storing raw data in <strong>S3</strong>, triggering <strong>SQS</strong> events, and finally transforming and loading into a <strong>lakehouse powered by Apache Iceberg</strong> — this project showcases how various AWS services work together to deliver a scalable and modern data architecture.</p><p>By following this project, you’ll gain practical experience and a solid understanding of AWS services such as EC2, IAM, S3, Kinesis, Firehose, SQS, and Glue, as well as foundational concepts of building a data lake house on the cloud.</p><h3><strong>REFERENCES:</strong></h3><ul><li><a href="https://stackoverflow.com/questions/48399903/what-is-partition-key-in-aws-kinesis-all-about">https://stackoverflow.com/questions/48399903/what-is-partition-key-in-aws-kinesis-all-about</a></li><li><a href="https://luminousmen.com/post/choosing-the-right-aws-storage-service-a-comprehensive-guide-to-s3-s3n-and-s3a">https://luminousmen.com/post/choosing-the-right-aws-storage-service-a-comprehensive-guide-to-s3-s3n-and-s3a</a></li><li><a href="https://medium.com/codebrace/working-with-json-jsonl-multiline-json-in-apache-spark-42b524a4724">https://medium.com/codebrace/working-with-json-jsonl-multiline-json-in-apache-spark-42b524a4724</a></li><li><a href="https://www.guptaakashdeep.com/copy-on-write-or-merge-on-read-apache-iceberg-2/">https://www.guptaakashdeep.com/copy-on-write-or-merge-on-read-apache-iceberg-2/</a></li><li><a href="https://iceberg.apache.org/">https://iceberg.apache.org/</a></li><li><a href="https://docs.snowflake.com/en/user-guide/tables-iceberg-configure-external-volume">https://docs.snowflake.com/en/user-guide/tables-iceberg-configure-external-volume</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e11df805e3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an End-to-End ETL Data Pipeline with Apache Airflow, AWS Redshift, and AWS Glue Crawler]]></title>
            <link>https://medium.com/@sanjay28.js/building-an-end-to-end-etl-data-pipeline-with-apache-airflow-aws-redshift-and-aws-glue-crawler-30543f112730?source=rss-67c434b1b944------2</link>
            <guid isPermaLink="false">https://medium.com/p/30543f112730</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[aws-redshift]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sanjay Jayakumar]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 18:17:39 GMT</pubDate>
            <atom:updated>2024-08-12T18:17:39.740Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Project Overview:</strong></h3><p>This project involves a robust ETL pipeline that begins with data stored in Amazon RDS, primarily serving OLTP purposes. The data is then transferred to Amazon S3, which acts as an intermediate storage layer. To facilitate efficient querying, AWS Glue Crawler is employed to scan the data in S3 and automatically generate metadata in the Glue Data Catalog. This metadata can be leveraged for querying the data directly from S3 using Amazon Athena or Amazon Redshift.</p><p>In this architecture, Amazon S3 acts as a staging area, allowing for the creation of an external schema in Amazon Redshift. This setup enables seamless access to the data in S3 through Redshift, where it is organized into landing tables. From these landing tables, dimension and fact tables are subsequently generated, forming the backbone of the data warehouse.</p><p>Apache Airflow plays a critical role in orchestrating the entire workflow. It automates the process of extracting data from RDS, loading it into S3, triggering the Glue Crawler to update the metadata, and executing the necessary SQL commands on Redshift.</p><p>The pipeline is designed to handle incremental loads, capturing only the data that has changed since the last ETL sync. This incremental approach ensures that the data warehouse is updated efficiently and in a timely manner, minimizing unnecessary data processing and enhancing overall performance.</p><p>By integrating these technologies — Amazon RDS, S3, Glue, Redshift, and Airflow — the project delivers a scalable and efficient data processing solution that supports advanced analytics and reporting.</p><p><strong>Dataset Link </strong>:<em>​ </em><a href="https://www.kaggle.com/datasets/yeanzc/telco-customer-churn-ibm-dataset?resource=download"><em>Telco customer churn: IBM dataset</em></a></p><p><strong>Repository </strong>: <a href="https://github.com/Sanjay-dev-ds/churn-data-analytics-data-pipeline.git">https://github.com/Sanjay-dev-ds/churn-data-analytics-data-pipeline.git</a></p><h3>ETL Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxLVlaNjI1oVHYApkACHTg.png" /><figcaption>ETL architecture</figcaption></figure><h3>Airflow DAG workflow diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0c-hLsYWC8OKGB9_JML1g.png" /></figure><h3>Main Steps to achieve this project</h3><ol><li>Setup airflow on EC2 Instance</li><li>Setup Raw Data on RDS</li><li>Setting up DAG on airflow</li></ol><blockquote><strong><em>Steps to Set Up Apache Airflow on an EC2 Instance</em></strong></blockquote><h4><strong>1. Create an EC2 Instance</strong></h4><ul><li><strong>Instance Type:</strong> Choose a t2.medium instance, which offers 2 vCPUs and 4 GB RAM, the minimum required to support Airflow efficiently.</li><li><strong>Security Group Configuration:</strong> Airflow runs on port 8080. Adjust the inbound rules in your security group to allow access from your IP address or open it up to 0.0.0.0/0 for universal access. This will enable you to access the Airflow web UI from your machine.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGq1SLXTxDelR3lluwXtmA.png" /><figcaption>| Security Group of EC2 Instance |</figcaption></figure><h4><strong>2. Add Host details in config</strong></h4><p>For easier access to your EC2 instance, add the host details to your SSH config file:</p><pre>cd ~/.ssh<br>vi config</pre><p>Then, add the following configuration:</p><pre>Host airflow<br>     HostName 44.201.254.61<br>     User ubuntu<br>     IdentityFile  ~/Documents/YOUR PEM KEY PATH</pre><p>This allows you to connect to the instance with:</p><pre>ssh airflow</pre><h4>3. Install Python and Set Up a Virtual Environment</h4><pre>sudo apt update<br>sudo apt install python3-pip<br>sudo apt install python3.12-venv</pre><p><strong>Create and Activate a Virtual Environment:</strong></p><pre># clone the project or create new project <br>mkdir churn-data-analytics-data-pipeline %% cd churn-data-analytics-data-pipeline<br><br>git clone https://github.com/Sanjay-dev-ds/churn-data-analytics-data-pipeline.git<br><br>python3 -m venv telco_venv<br>source telco_venv/bin/activate</pre><p>Install the necessary packages:libraries</p><pre>pip install apache-airflow<br>pip install apache-airflow-providers-amazon<br>pip install &#39;apache-airflow[postgres]&#39;<br>pip install pandas<br>pip install pyarrow</pre><h4>4. Start the Airflow Instance</h4><pre>airflow standalone<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGeiq1bcSIDYCwJVe76_Ew.png" /><figcaption>Airflow Login UI</figcaption></figure><p><strong>Access the Airflow UI:</strong> Use the public IP address of your EC2 instance and port 8080 to access the UI, e.g., <a href="http://your_ec2_public_ip:8080/">http://YOUR_EC2_PUBLIC_IP:8080/.</a></p><p>Copy IP from EC2 instance’s summary content</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*dH5jwMBjMQIEMD8sFNqbyw.png" /></figure><h4>5. Configure airflow.cfg</h4><p>The airflow folder is located in the root directory of your instance. To configure airflow :</p><ul><li>cd airflow vi airflow.cfg</li></ul><p><strong>Update the DAGs Folder Path:</strong></p><pre>dags_folder = /home/ubuntu/churn-data-analytics-data-pipeline/dags<br># create dags folders under churn-airflow-data-pipeline folder (project folder)</pre><p><strong>Disable Example DAGs:</strong></p><pre>load_examples = False</pre><p><strong>Restart the Airflow Server:</strong> After making these changes, restart the Airflow server to apply the new configuration.</p><blockquote><strong>Steps to Set Up Raw Data on RDS</strong></blockquote><h4>Create an RDS Instance with PostgreSQL</h4><ol><li><strong>RDS Instance Setup</strong></li></ol><p><strong>Database Engine:</strong> Select PostgreSQL as the DB engine for your RDS instance.</p><p><strong>Public Access:</strong></p><ul><li>If you plan to access the database from your laptop, enable public access.</li><li>If you are accessing the database from your EC2 instance, public access is not required, as internal communication is sufficient.</li></ul><p><strong>2. Load Sample Data into RDS</strong></p><ul><li>In this <a href="https://github.com/Sanjay-dev-ds/churn-data-analytics-data-pipeline/blob/main/raw_data/data_generator_notebook.ipynb">GitHub repository</a>, under the raw_data folder, you’ll find a Jupyter notebook designed to load sample data into your RDS instance.</li><li>This notebook will load 5% of the raw data into the RDS database. The record_modified field in the data can be particularly useful for change data capture (CDC) in subsequent processes.</li></ul><blockquote><strong><em>Creating an Airflow DAG for ETL: Ingesting Data from RDS to S3</em></strong></blockquote><p><strong>Prerequisites of DAG : </strong>Create an S3 bucket and IAM role using the CloudFormation template provided in the following link: <a href="https://github.com/Sanjay-dev-ds/churn-data-analytics-data-pipeline/blob/airflow_implementation/resources_cft.yaml">CloudFormation Template — Churn Data Analytics Data Pipeline</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*UhNc6ANUxNtjY-8lWwVp8w.png" /></figure><h4>Concept Overview</h4><p><strong>Objective:</strong></p><ul><li>We treat the RDS as an OLTP (Online Transaction Processing) system. Our goal is to move data from this transactional database to an S3 bucket, which serves as a Data Lake for further processing.</li><li>We’ll use Airflow variables to track the last ETL run, ensuring that only new or modified data is processed during subsequent runs.</li></ul><p><strong>Workflow:</strong></p><ul><li>Extract data from the RDS instance based on a record_modified timestamp.</li><li>Ingest this data into an S3 bucket as Parquet files, a common format for big data processing.</li></ul><ol><li>Get Last ETL sync time</li></ol><p>First, we need to retrieve the timestamp of the last successful ETL run. This is done using an Airflow variable:</p><pre>@task<br> def get_last_etl_sync():<br> record_modified = Variable.get(&#39;record_modified&#39;, default_var=None)<br> return record_modified</pre><ul><li>If this variable doesn’t exist, it returns None, indicating that no previous ETL run has been recorded.</li></ul><p>2. Task Group: Extract and Ingest Data</p><ul><li><strong>Task Group:</strong> This logical grouping of tasks ensures that the data extraction and ingestion processes are managed together.</li></ul><pre>   @task_group<br>    def ingest_data_task_group(record_modified):<br>        df = extract_data(record_modified)<br>        current_timestamp =  datetime.now()<br>        s3_key = f&#39;{s3_prefix}/{current_timestamp.strftime(&#39;%Y%m%d%H%M%S&#39;)}/{table_name}.csv&#39;<br>        ingest_data_into_s3(df, s3_bucket, s3_key)<br>        Variable.set(&#39;record_modified&#39;, current_timestamp)</pre><p><strong>ingest_data_task_group contain two task</strong></p><ul><li><strong>@task extract_data</strong></li></ul><p>This task connects to the RDS instance and fetches data using a timestamp filter.</p><pre>    @task<br>    def extract_data(record_modified=None):<br>        pg_hook = PostgresHook(postgres_conn_id=&#39;telco_postgres_conn_id&#39;)<br>        with pg_hook.get_conn() as conn:<br>            cursor = conn.cursor()<br><br>            if record_modified is None:<br>                query = f&#39;SELECT * FROM {schema_name}.{table_name};&#39;<br>                print(query)<br>                cursor.execute(query)<br>            else:<br>                query = f&#39;SELECT * FROM {schema_name}.{table_name} WHERE record_modified &gt; %s;&#39;<br>                cursor.execute(query, (record_modified,))<br><br>            rows = cursor.fetchall()<br>            df = pd.DataFrame(rows, columns=[desc[0] for desc in cursor.description])<br>            print(&quot;Number of records : &quot;,len(df))<br>            <br>            conn.commit()<br>            cursor.close() <br>            return df</pre><p><strong>Querying Data:</strong></p><ul><li>If record_modified is None (indicating the first ETL run), all records are fetched from the table.</li><li>Otherwise, only records modified since the last ETL run are retrieved.</li></ul><p>The fetched data is converted into a Pandas DataFrame, which is returned for further processing.</p><ul><li><strong>@task ingest_data_into_s3</strong></li></ul><p>Provide AWS credentials for aws_default for accessing AWS services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*XTg6j9zb_xFK7fgGnE0tCw.png" /></figure><p>Once the data is extracted, the next step is to load it into an S3 bucket.</p><pre>   @task<br>    def ingest_data_into_s3(df: DataFrame, s3_bucket: str, s3_key: str):<br>        hook = S3Hook(aws_conn_id=&#39;aws_default&#39;)<br>        buffer = StringIO()<br>        df.to_parquet(buffer, index=False)<br>        # df.to_csv(buffer, index=False)<br>        buffer.seek(0)<br>        hook.load_string(buffer.getvalue(), key=s3_key, bucket_name=s3_bucket)<br>        print(f&quot;DataFrame ingested into s3://{s3_bucket}/{s3_key}&quot;)</pre><p><strong>S3Hook:</strong> This hook manages connections to S3 using the aws_default connection ID in Airflow.</p><p>The Parquet file is uploaded to the specified S3 bucket and key. The use of StringIO allows in-memory operations, which are more efficient than writing to disk.</p><blockquote><strong><em>Creating an Airflow DAG for ETL: Trigger Glue Crawler</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*nS2pynRlY_c90WVVAh6JPg.png" /></figure><p>Glue Crawlers are a powerful tool for automatically cataloging your data stored in Amazon S3, making it available for querying and analytics in services like AWS Athena or Redshift Spectrum</p><ol><li>Create glue crawler</li></ol><p>The data source for the crawler will be an S3 bucket containing the datasets you wish to catalog.</p><p>We’ll configure the crawler to run on-demand and only crawl new sub-folders, meaning it will only scan for data added since the last crawl, ensuring efficient updates without redundant processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*JDSmSjFAETbDsXCLyVP2_Q.png" /></figure><p>Create Database : <strong><em>Telco</em></strong></p><p>Table prefix : <strong><em>landing_</em></strong></p><p>Assign a table prefix, such as landing_, to help differentiate the tables created by this crawler from others.</p><p>Set the crawler to run on-demand, meaning it will be triggered by Airflow rather than running on a fixed schedule.</p><p>Ensure that the crawler uses an IAM role created by a CloudFormation Template (CFT), which grants it the necessary permissions to access the S3 bucket and manage the Glue Catalog.</p><p>2. Trigger glue crawler</p><pre>    @task<br>    def trigger_glue_crawler():<br>        return GlueCrawlerOperator(<br>            task_id=&#39;run_glue_crawler&#39;,<br>            config={&#39;Name&#39;: glue_crawler_name},<br>            aws_conn_id=&#39;aws_default&#39;,<br>            wait_for_completion = True,<br>            region_name = REGION,<br>            poll_interval = 10<br>        ).execute(context={})</pre><ul><li>wait_for_completion=True: This ensures that the task waits for the Glue Crawler to complete its execution before moving on to the next task in the DAG.</li><li>poll_interval=10: This sets the interval (in seconds) at which the operator checks the status of the Glue Crawler job.</li></ul><blockquote><strong><em>Creating an Airflow DAG for ETL: Creation of Stage Layer</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*w5Tf4BIThAyaf_FbaXJkfQ.png" /></figure><p>Maintaining a staging layer in Amazon Redshift. This staging layer serves as an intermediate step in ETL</p><h4>1. Creating the Schema and Tables in Redshift</h4><p>The first step in our DAG is to create the necessary schemas and tables in Redshift.</p><p>The task reads an SQL file (create_relevant_schema.sql) containing the necessary SQL statements to create schemas and tables. It executes each statement one by one.</p><pre>def create_relevant_schema_on_redshift():<br>    redshift_hook = RedshiftSQLHook(redshift_conn_id=&#39;redshift_default&#39;)<br>    with redshift_hook.get_conn() as conn:<br>        cursor = conn.cursor()<br>        sql_file_path = &#39;dags/sql/create_relevant_schema.sql&#39;<br>        with open(sql_file_path, &#39;r&#39;) as file:<br>            query = file.read()<br>        for stmt in query.strip().split(&#39;;&#39;):<br>            if stmt.strip():<br>                print(&quot;Executing : &quot;, stmt)<br>                cursor.execute(stmt)<br>        conn.commit()<br>        cursor.close()</pre><p><em>create_relevant_schema.sql :</em></p><pre>CREATE SCHEMA IF NOT EXISTS telco_internal;<br>CREATE EXTERNAL SCHEMA IF NOT EXISTS telco_external<br>FROM DATA CATALOG<br>DATABASE &#39;telco_meta_db&#39;<br>IAM_ROLE &#39;arn:aws:iam::&lt;AWS_ACCOUNT_ID&gt;:role/telcoIAMrole&#39;<br>CREATE EXTERNAL DATABASE IF NOT EXISTS;</pre><p>2. Create Control table (Common)</p><p>required across multiple stages of the ETL process, To Sync time of each tables across stages</p><pre>CREATE TABLE IF NOT EXISTS telco_internal.control_table (<br>    table_name VARCHAR(255) PRIMARY KEY,<br>    last_load_timestamp TIMESTAMP<br>);</pre><p>3. Creating Stage table and Inserting Data from External schema (S3)</p><p>Executed by @task def create_or_populate_staging_table():</p><ul><li>This will create table if not exists</li><li>Insert by last_load from external table, Populated by Glue crawler</li></ul><pre>INSERT INTO telco_internal.staging_telco_customer_churn_data (<br>    CustomerID, Count, Country, State, City, Zip_Code,<br>    Latitude, Longitude, Gender, SeniorCitizen, Partner, Dependents,<br>    Tenure, PhoneService, MultipleLines, InternetService, OnlineSecurity,<br>    OnlineBackup, DeviceProtection, TechSupport, StreamingTV, StreamingMovies,<br>    Contract, PaperlessBilling, PaymentMethod, MonthlyCharges, TotalCharges,<br>    Churn_Label, Churn_Value, Churn_Score, CLTV, Churn_Reason, Record_Modified<br>)<br>WITH last_load AS (<br>    SELECT last_load_timestamp<br>    FROM telco_internal.control_table<br>    WHERE table_name = &#39;telco_internal.staging_telco_customer_churn_data&#39;<br>)<br>SELECT<br>    DISTINCT CustomerID, Count, Country, State, City, &quot;zip code&quot;,<br>    Latitude, Longitude, Gender, &quot;senior citizen&quot;, Partner, Dependents,<br>    &quot;tenure months&quot;, &quot;phone service&quot;, &quot;multiple lines&quot;, &quot;internet service&quot;, &quot;online security&quot;,<br>    &quot;online backup&quot;, &quot;device protection&quot;, &quot;tech support&quot;, &quot;streaming tv&quot;, &quot;streaming movies&quot;,<br>    Contract, &quot;paperless billing&quot;, &quot;payment method&quot;, &quot;monthly charges&quot;, &quot;total charges&quot;,<br>    &quot;churn label&quot;, &quot;churn value&quot;, &quot;churn score&quot;, &quot;cltv&quot;, &quot;churn reason&quot;, &quot;record_modified&quot;<br>FROM telco_external.landing_telco_customer_churn_data<br>WHERE &quot;record_modified&quot; &gt; (SELECT COALESCE(MAX(last_load_timestamp), &#39;1900-01-01&#39;) FROM last_load);</pre><p>4. Updating the Last Sync Time</p><p>This task updates the control_table in Redshift, which tracks the last time data was loaded for each table. This is crucial for performing incremental loads, where only new or updated data is processed.</p><pre>@task<br>def update_last_sync_time(table_name):<br>    print(&#39;Updating sync time&#39;)<br>    redshift_hook = RedshiftSQLHook(redshift_conn_id=&#39;redshift_default&#39;)<br>    with redshift_hook.get_conn() as conn:<br>        cursor = conn.cursor()<br>        sql_file_path = &#39;dags/sql/update_last_etl_sync.sql&#39;<br>        with open(sql_file_path, &#39;r&#39;) as file:<br>            query = file.read()<br>            formatted_query = query.format(table_name=table_name)<br>            print(formatted_query)<br>        for stmt in formatted_query.strip().split(&#39;;&#39;):<br>            if stmt.strip():<br>                print(&quot;Executing : &quot;, stmt)<br>                cursor.execute(stmt)<br>        conn.commit()<br>        cursor.close()</pre><p><strong>Next :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*w2GCljadinQ0beXUqzHEdg.png" /></figure><p><strong>Dimension and Fact Table Creation:</strong> The creation of dimension and fact tables follows a similar pattern. The required code can be found in the repository. If you encounter any issues or have suggestions, feel free to reach out to me on LinkedIn. Thank you for reading !</p><blockquote><strong><em>Author: Sanjay Jayakumar<br>Data Engineer</em></strong></blockquote><h3><strong>References</strong></h3><p><a href="https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/_api/airflow/providers/amazon/aws/operators/glue_crawler/index.html">airflow.providers.amazon.aws.operators.glue_crawler - apache-airflow-providers-amazon Documentation</a></p><p><a href="https://stackoverflow.com/questions/75460711/no-module-named-airflow-providers-amazon-aws-hooks-redshift">https://stackoverflow.com/questions/75460711/no-module-named-airflow-providers-amazon-aws-hooks-redshift</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30543f112730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless Data Pipeline: A Step-by-Step Guide]]></title>
            <link>https://towardsdev.com/building-a-serverless-data-pipeline-a-step-by-step-guide-a5a65c721eb0?source=rss-67c434b1b944------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5a65c721eb0</guid>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[athena]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sanjay Jayakumar]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 17:21:20 GMT</pubDate>
            <atom:updated>2024-07-18T17:08:03.965Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Welcome to this project! Our aim is to provide foundational knowledge in data engineering to help you create a serverless data pipeline.</strong></p><p><strong>Project Overview</strong></p><p>This project demonstrates building a serverless data pipeline using AWS services. AWS Lambda fetches data from the Colombo Stock Market Index API and ingest it directly into Amazon Kinesis Data Firehose and it stored data into S3.</p><p>S3 triggers event notifications to an SQS queue upon new data arrival. Glue crawler recrawl the data based on these events.</p><p>AWS Glue Workflow then orchestrates ETL jobs executed with Python shell scripts. Amazon Athena creates and manages Apache Iceberg tables for efficient merge operations, with AWS Glue Catalog managing the metadata.</p><p>This Serverless Framework configuration defines a data pipeline on AWS, employing various services including AWS Lambda, S3, SQS, and Kinesis Firehose.</p><p><strong>Prerequisites</strong></p><p>To follow along with this project, you will need:</p><ul><li>Serverless Framework — Used as Infrastructure as Code</li><li>Python</li><li>AWS Cloud account</li></ul><p><strong>Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yo6M4OiSxOhChIGanmmW2A.png" /></figure><p><strong>Phase 1: Data Extraction and Ingestion</strong></p><p>In the first phase, we utilize AWS Lambda function to fetch data from the <strong>Colombo Stock Market Index</strong> API. The extracted data is then sent to Amazon Kinesis Data Firehose as JSON objects.</p><p><strong><em>AWS Lambda</em></strong> is a serverless compute service where you write code and upload it. It runs that code in response to events like file uploads, API requests, or triggers from services like Amazon<strong> <em>EventBridge</em></strong>. This frees you from server management and lets you focus on your code. You only pay for the time your code runs, making it cost-effective and scalable for various tasks</p><p><strong><em>AWS Firehose</em></strong> is a data pipeline service for real-time streaming data. It continuously ingests data from sources like application logs or Kinesis streams or custom producer, can transform it to a specific format, and then delivers it to various destinations like <strong><em>data lakes</em></strong><em> </em>(S3) or analytics services (OpenSearch) for further processing. This simplifies managing streaming data pipelines, reduces complexity by automating delivery and scaling</p><p>In this project, we use an Amazon S3 bucket as the destination for the Kinesis Data Firehose stream, with AWS Lambda acting as the producer application. The Lambda function uses <strong><em>DIRECT PUT</em></strong> to stream data to the Firehose. The Firehose stream is configured with a buffer hint of either a 5-minute interval or a 5 KB size, ensuring efficient and timely data delivery to S3.</p><p>AWS EventBridge allows you to schedule events using cron expressions. Cron expressions are a powerful way to define precise scheduling patterns. Data extractor Lambda function invokes daily at 8 AM UTC by event bridge rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*7_jM4pUaIi-XFZIkzTBB5w.png" /></figure><pre>def lambda_handler(event, context):<br>    http = urllib3.PoolManager()<br><br>    r = http.request(&quot;POST&quot;, &quot;https://www.cse.lk/api/aspiData&quot;)<br><br>    # turn it into a dictionary<br>    r_dict = json.loads(r.data.decode(encoding=&#39;utf-8&#39;, errors=&#39;strict&#39;))<br><br>    # extract pieces of the dictionary<br>    processed_dict = {}<br>    processed_dict[&#39;id&#39;] = r_dict[&#39;id&#39;]<br>    processed_dict[&#39;aspi_value&#39;] = r_dict[&#39;value&#39;]<br>    processed_dict[&#39;lowValue&#39;] = r_dict[&#39;lowValue&#39;]<br>    processed_dict[&#39;highValue&#39;] = r_dict[&#39;highValue&#39;]<br>    processed_dict[&#39;change&#39;] = r_dict[&#39;change&#39;]<br>    processed_dict[&#39;sectorId&#39;] = r_dict[&#39;sectorId&#39;]<br>    processed_dict[&#39;timestamp&#39;] = r_dict[&#39;timestamp&#39;]<br><br>    # turn it into a string and add a newline<br>    msg = str(processed_dict) + &#39;\n&#39;<br><br>    fh = boto3.client(&#39;firehose&#39;)<br><br>    reply = fh.put_record(<br>        DeliveryStreamName=FIREHOSE_NAME,<br>        Record={<br>            &#39;Data&#39;: msg<br>        }<br>    )<br><br>    return msg</pre><p>The lambda_handler function fetches ASPI (All Share Price Index) data from the CSE API and processes it for storage in AWS Kinesis Firehose. Using urllib3, it sends a POST request to &quot;<a href="https://www.cse.lk/api/aspiData">https://www.cse.lk/api/aspiData</a>&quot; and decodes the JSON response. Key data fields such as &#39;id&#39;, &#39;value&#39;, &#39;lowValue&#39;, &#39;highValue&#39;, &#39;change&#39;, &#39;sectorId&#39;, and &#39;timestamp&#39; are extracted and formatted into a string. This string is then sent to a Firehose delivery stream using the boto3 library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zjt9lYChnahgqlTC_OteQQ.png" /><figcaption>Data Firehose with Source as Direct PUT and Destination as S3</figcaption></figure><p><strong>Phase 2: Event Notification and Processing</strong></p><p>Data landing in the S3 bucket automatically triggers a notification to a dedicated SQS queue, An AWS Glue crawler is configured to re-crawl based on new events by consuming the SQS.</p><p>An AWS SQS Standard Queue is a high-throughput, cost-effective messaging queue that ensures messages are delivered at least once, but potentially out of order and with duplicates. It’s ideal for situations where order isn’t critical and you need to handle a large volume of messages.</p><p>Glue crawler consume this Queue to recrawl the S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ly-3HulDuH0H9J8mB3XqbA.png" /></figure><p><strong>Messages available</strong> are the messages that are present in the queue and ready to be read by consumers. These messages are in a state where they can be delivered to any consumer that polls the queue.</p><p><strong>Messages in flight</strong> are the messages that have been received by a consumer but have not yet been deleted from the queue. When a consumer receives a message, it is temporarily hidden from other consumers for a specified period called the visibility timeout.</p><p><strong>Phase 3: Crawling and Querying Data lake</strong></p><p><strong><em>AWS Glue crawler </em></strong>used to populate the AWS Glue Data Catalog with databases and tables. A crawler can crawl multiple data stores in a single run. Upon completion, the crawler creates or updates one or more tables in Data Catalog. ETL jobs that define in AWS Glue use these Data Catalog tables as sources and targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDjPd8KCHI6szNcfd1QSHQ.png" /><figcaption>AWS Glue crawler configured to recrawl by events</figcaption></figure><p><strong><em>The AWS Glue Data Catalog</em></strong> is persistent technical metadata store. It is a managed service that can use to store, annotate, and share metadata in the AWS Cloud</p><p>In this project raw table has been created as Data catalog table using S3 bucket which contains JSON objects.</p><p>AWS Athena can be used to query Data catalog tables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjDKi_VNnz-xvv3OO6ye8A.png" /></figure><p><strong>Phase 5: Orchestration and ETLs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukFwj07oNhP2INYNBf5kgg.png" /></figure><p><strong><em>AWS Glue workflows</em></strong> allow you to automate and manage complex data processing tasks. They combine crawlers to discover data sources, ETL jobs to clean and transform the data, and triggers to initiate the workflow based on a schedule or events. This visual workflow builder provides a clear view of your entire data pipeline, making it easier to monitor, troubleshoot, and scale your data processing needs in AWS Glue.</p><p>Create Stage Table : This step involves creating an external Parquet table. The process includes applying necessary transformations to the raw data from the AWS Glue catalog table.</p><p>2.Data Quality check : This step performs data quality validation to check for NULL values in the table. If the validation conditions are not met, this node will transition to a failure state.</p><p>3. Create Prod table : This step involves creating the production table as an Apache Iceberg table.</p><pre>query = f&quot;&quot;&quot;<br>    CREATE TABLE {PROD_TABLE_NAME} (<br>        cse_aspi_index_id int,<br>        cse_aspi_value float,<br>        cse_aspi_low_value float,<br>        cse_aspi_high_value float,<br>        cse_aspi_change float,<br>        cse_aspi_sector_id int,<br>        ist_timestamp timestamp<br>    )<br>    LOCATION &#39;{PROD_TABLE_S3_BUCKET}&#39;<br>    TBLPROPERTIES ( &#39;table_type&#39; = &#39;ICEBERG&#39; );<br>    &quot;&quot;&quot;</pre><p>4. Publish Prod Table : In this step, data from the Stage table is merged into the Production table using a merge operation, if index_id matches the prod table, record will be updated</p><p><strong>Query used for merge operation :</strong></p><pre>query = f&quot;&quot;&quot;<br>    MERGE INTO {PROD_TABLE_NAME} AS target<br>    USING (<br>        -- Select the unique records with the latest timestamp<br>        WITH LatestRecords AS (<br>            SELECT<br>                cse_aspi_index_id,<br>                cse_aspi_value,<br>                cse_aspi_low_value,<br>                cse_aspi_high_value,<br>                cse_aspi_change,<br>                cse_aspi_sector_id,<br>                CAST(ist_timestamp AS TIMESTAMP(6)) AS ist_timestamp,<br>                ROW_NUMBER() OVER (PARTITION BY cse_aspi_index_id ORDER BY cse_aspi_timestamp DESC) AS rn<br>            FROM {STAGE_TABLE_NAME}<br>        )<br>        SELECT<br>            cse_aspi_index_id,<br>            cse_aspi_value,<br>            cse_aspi_low_value,<br>            cse_aspi_high_value,<br>            cse_aspi_change,<br>            cse_aspi_sector_id,<br>            ist_timestamp<br>        FROM LatestRecords<br>        WHERE rn = 1<br>    ) AS source<br>    ON target.cse_aspi_index_id = source.cse_aspi_index_id<br>    WHEN MATCHED THEN<br>        UPDATE SET<br>            cse_aspi_value = source.cse_aspi_value,<br>            cse_aspi_low_value = source.cse_aspi_low_value,<br>            cse_aspi_high_value = source.cse_aspi_high_value,<br>            cse_aspi_change = source.cse_aspi_change,<br>            cse_aspi_sector_id = source.cse_aspi_sector_id,<br>            ist_timestamp = source.ist_timestamp<br>    WHEN NOT MATCHED THEN<br>        INSERT (<br>            cse_aspi_index_id,<br>            cse_aspi_value,<br>            cse_aspi_low_value,<br>            cse_aspi_high_value,<br>            cse_aspi_change,<br>            cse_aspi_sector_id,<br>            ist_timestamp<br>        ) VALUES (<br>            source.cse_aspi_index_id,<br>            source.cse_aspi_value,<br>            source.cse_aspi_low_value,<br>            source.cse_aspi_high_value,<br>            source.cse_aspi_change,<br>            source.cse_aspi_sector_id,<br>            source.ist_timestamp<br>        );<br>    ;<br>    &quot;&quot;&quot;</pre><p>The subquery LatestRecords identifies unique records with the most recent timestamp from the staging table by assigning a row number (rn) to each record, partitioned by cse_aspi_index_id and ordered by cse_aspi_timestamp in descending order. The condition WHERE rn = 1 ensures that only the latest record for each cse_aspi_index_id is selected. The main query then uses a MERGE INTO statement to merge data from the subquery (source) into the production table. The matching condition ON target.cse_aspi_index_id = source.cse_aspi_index_id checks if a record in the production table has the same cse_aspi_index_id as a record in the source. If a matching record is found, the existing record in the production table is updated with the new values from the source. If no matching record is found, a new record is inserted into the production table with the values from the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POvSgfS3mIB4egBhnUH_qQ.png" /><figcaption>AWS Glue Catalog Tables</figcaption></figure><blockquote>Author : <a href="https://www.linkedin.com/in/sanjay-dev-ds/">Sanjay Jayakumar</a></blockquote><p><strong>References</strong></p><ul><li><a href="https://iceberg.apache.org/">Apache Iceberg™</a></li><li><a href="https://cse.lk/">Colombo Stock Exchange</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5a65c721eb0" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/building-a-serverless-data-pipeline-a-step-by-step-guide-a5a65c721eb0">Building a Serverless Data Pipeline: A Step-by-Step Guide</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spam-Ham Email Detection]]></title>
            <link>https://medium.com/@sanjay28.js/spam-ham-email-detection-240e7992acf9?source=rss-67c434b1b944------2</link>
            <guid isPermaLink="false">https://medium.com/p/240e7992acf9</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Sanjay Jayakumar]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 05:52:44 GMT</pubDate>
            <atom:updated>2022-12-27T05:52:44.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Detect emails whether spam or ham using Support Vector Machine and Natural language Processing.</p><p><em>By Opening Google Collab you can start coding (No Need Download Anything).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*S3A2qt0mZe5OvrBpNDYNUQ.png" /></figure><p><strong>Import Relevant Libraries</strong></p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split , GridSearchCV , KFold<br>from sklearn.svm import SVC <br>from sklearn.metrics import accuracy_score , classification_report , confusion_matrix<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import re<br>import nltk<br>from nltk.stem import PorterStemmer<br>from sklearn import metrics<br>from sklearn.feature_extraction.text import CountVectorizer</pre><p><strong>Import dataset from GitHub</strong></p><pre>df = pd.read_csv(&quot;https://raw.githubusercontent.com/Sanjay-dev-ds/spam_ham_email_detector/master/spam.csv&quot;)<br>df.head()</pre><h3><strong>Data-Preprocessing</strong></h3><p><em>Remove duplicate values</em></p><pre>df = df.drop_duplicates(keep=&#39;first&#39;)</pre><p><em>Split into Independent and dependent variable</em></p><pre>x = df[&#39;EmailText&#39;].values<br>y = df[&#39;Label&#39;].values</pre><h3><strong>Text Pre-Processing</strong></h3><p>creating a function to lowercase the text, remove special characters, normalize certain words, use stems of words instead of the original form using porter stemmer algorithm.</p><pre>porter_stemmer=PorterStemmer()<br>def preprocessor(text):<br>    <br>    text=text.lower() <br>    text=re.sub(&quot;\\W&quot;,&quot; &quot;,text) <br>    text=re.sub(&quot;\\s+(in|the|all|for|and|on)\\s+&quot;,&quot; _connector_ &quot;,text) <br>    words=re.split(&quot;\\s+&quot;,text)<br>    stemmed_words=[porter_stemmer.stem(word=word) for word in words]<br>    return &#39; &#39;.join(stemmed_words)</pre><p>creating tokenizer function to</p><ol><li>Create a space between special characters</li><li>Split based on whitespace</li></ol><pre>def tokenizer(text):<br>    text=re.sub(&quot;(\\W)&quot;,&quot; \\1 &quot;,text)<br>    return re.split(&quot;\\s+&quot;,text)</pre><h3><strong>Count Vectorizer is used to transform a corpus of text to a vector of term.</strong></h3><p><em>min_df = 0.06 ( taking 0.6% of Minimum Document Frequency )</em></p><p><em>ngram_range=(1,2) ( word level Unigrams and bigrams)</em></p><pre>vectorizer = CountVectorizer(tokenizer=tokenizer,ngram_range=(1,2),min_df=0.006,preprocessor=preprocessor)<br>x  = vectorizer.fit_transform(x)</pre><h3><strong>Check Data is imbalanced</strong></h3><pre>sns.countplot(df[&#39;Label&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*wn2KxWfKOAL2OsGnwtqtyg.png" /></figure><p>target class has an uneven distribution of observations, So we are using random over sampling method to balance the target variable’s observation</p><p><strong>Random Oversampling: </strong>randomly duplicate examples in the minority class (Spam)</p><pre>from imblearn.under_sampling import NearMiss<br>from collections import Counter<br>from imblearn.over_sampling import RandomOverSampler<br><br>ros = RandomOverSampler(random_state=42)<br><br>print(&#39;Original dataset shape&#39;, Counter(y))<br><br># fit predictor and target <br>x,y = ros.fit_resample(x, y)<br><br>print(&#39;Modified dataset shape&#39;, Counter(y))</pre><blockquote><strong><em>OUTPUT</em></strong></blockquote><blockquote><em>Original dataset shape Counter({‘ham’: 4516, ‘spam’: 653})</em></blockquote><blockquote><em>Modified dataset shape Counter({‘ham’: 4516, ‘spam’: 4516})</em></blockquote><p>Here, After balancing the dataset, You can see Spam Dataset has been duplicated.</p><h3>Build SVM Model</h3><p><strong>Split into training and testing set</strong></p><p>Using 80% of data for training with Random State 0.</p><pre>x_train , x_test , y_train , y_test   = train_test_split(x, y, test_size =0.2,random_state = 0)<br><br></pre><p><strong>Build SVM model and fit it using training data</strong></p><pre>model   = SVC(C =1,kernel = &quot;linear&quot; )<br>model.fit(x_train,y_train)</pre><p><strong>Check accuracy score</strong></p><pre>accuracy = metrics.accuracy_score(y_test, model.predict(x_test))<br>accuracy_percentage = 100 * accuracy<br>accuracy_percentage</pre><blockquote>98.83785279468734</blockquote><h3><strong>Hyperparameter Optimization using Grid Search CV</strong></h3><pre>params  = {&quot;C&quot;:[0.2,0.5] , &quot;kernel&quot; : [&#39;linear&#39;, &#39;sigmoid&#39;] }<br><br>cval = KFold(n_splits = 2)<br>model =  SVC();<br>TunedModel = GridSearchCV(model,params,cv= cval)<br><br><br>TunedModel.fit(x_train,y_train)<br><br></pre><p><strong>Accuracy of tuned model</strong></p><pre>accuracy = metrics.accuracy_score(y_test, TunedModel.predict(x_test))<br>accuracy_percentage = 100 * accuracy<br>accuracy_percentage</pre><p><strong>Confusion Matrix</strong></p><pre>sns.heatmap(confusion_matrix(y_test,TunedModel.predict(x_test)),annot = True , fmt =&quot;g&quot;)<br>plt.xlabel(&quot;Predicted&quot;)<br>plt.show(&quot;Actual&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*-P5TGHNZZOyDWWa3YFvK9Q.png" /></figure><p><strong>classification report</strong></p><pre>print(classification_report(y_test,TunedModel.predict(x_test)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*sapjSlzxZ5wwYtkn67EyoQ.png" /></figure><h3>Using the trained model, predict whether the following five emails are spam or ham 📧</h3><pre>mails = [&quot;Hey, you have won a car !!!!. Conrgratzz&quot;<br>              ,&quot;Dear applicant, Your CV has been recieved. Best regards&quot;<br>              ,&quot;You have received $1000000 to your account&quot;<br>              ,&quot;Join with our whatsapp group&quot;<br>              ,&quot;Kindly check the previous email. Kind Regard&quot;]<br>for mail in mails:<br>  is_spam = TunedModel.predict(vectorizer.transform([mail]).toarray())<br>  print(mail + &quot; : &quot;+ is_spam)</pre><p><strong>OUTPUT</strong></p><blockquote>[‘Hey, you have won a car !!!!. Conrgratzz : spam’]</blockquote><blockquote>[‘Dear applicant, Your CV has been recieved. Best regards : ham’]</blockquote><blockquote>[‘You have received $1000000 to your account : spam’]</blockquote><blockquote>[‘Join with our whatsapp group : ham’]</blockquote><blockquote>[‘Kindly check the previous email. Kind Regard : ham’]</blockquote><h3>Q&amp;A</h3><p><strong>1.What does random state 0 mean?</strong></p><p><em>With random_state=None , we get different train and test sets across different executions and the shuffling process is out of control. With random_state=0 , we get the same train and test sets across different executions</em></p><p><strong>2.What is Count Vectorizer In NLP?</strong></p><p><em>Count Vectorizer means breaking down a sentence or any text into words by performing preprocessing tasks like converting all words to lowercase, thus removing special characters</em></p><p><strong>3.What is confusion matrix ?</strong></p><p><em>A Confusion matrix is an N x N matrix used for evaluating the performance of a classification model, where N is the number of target classes. The matrix compares the actual target values with those predicted by the machine learning model</em></p><p><strong>4.What is Grid Search?</strong></p><p><em>GridSearchCV is a technique to search through the best parameter values from the given set of the grid of parameters. It is basically a cross-validation method. the model and the parameters are required to be fed in. Best parameter values are extracted and then the predictions are made</em></p><p><strong>for notebook and dataset:</strong></p><p><a href="https://github.com/Sanjay-dev-ds/spam_ham_email_detector">https://github.com/Sanjay-dev-ds/spam_ham_email_detector</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240e7992acf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>