<?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 Mingweig on Medium]]></title>
        <description><![CDATA[Stories by Mingweig on Medium]]></description>
        <link>https://medium.com/@mingweig99?source=rss-bb308b7cb435------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AllQngkJGN9XsYzI</url>
            <title>Stories by Mingweig on Medium</title>
            <link>https://medium.com/@mingweig99?source=rss-bb308b7cb435------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:43:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mingweig99/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[Streamlining ETL Workflows for Machine Learning with Apache Airflow, Kafka, and Google BigQuery]]></title>
            <link>https://medium.com/@mingweig99/streamlining-etl-workflows-for-machine-learning-with-apache-airflow-kafka-and-google-bigquery-1436081c5943?source=rss-bb308b7cb435------2</link>
            <guid isPermaLink="false">https://medium.com/p/1436081c5943</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Mingweig]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 01:18:58 GMT</pubDate>
            <atom:updated>2024-03-27T03:27:07.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swhNRJjp_9u9E2Zr6Vyl4A.png" /><figcaption>ETL Pipeline</figcaption></figure><h3><strong>Introduction</strong></h3><p>In the fast-paced world of machine learning and data science, the ability to efficiently process and manage data can significantly impact the insights derived and the effectiveness of machine learning models. This blog post explores an end-to-end<strong> Extract, Transform, Load (ETL)</strong> workflow using <strong>Apache Airflow</strong> for orchestration, <strong>Apache Kafka</strong> for real-time data streaming, and <strong>Google BigQuery</strong> for data storage and analysis. We’ll dive into a hands-on example that illustrates how these tools can work together to streamline data processing tasks in a production environment.</p><h3>Why ETL Matters in Machine Learning</h3><p><strong>ETL</strong> processes are the backbone of data preparation in machine learning. They allow us to automate the <strong>extraction</strong> of data from various sources, <strong>transform</strong> this data into a more usable format, and <strong>load</strong> it into a storage system for further analysis or model training. Efficient ETL processes not only save valuable time but also ensure that data is accurate, consistent, and readily available for machine learning applications.</p><h3>Exploring the Tools</h3><ul><li><strong>Apache Airflow</strong>: An open-source platform designed to programmatically author, schedule, and monitor workflows. Airflow excels in managing complex data pipelines by providing robust scheduling features and the ability to monitor the lifecycle of your workflow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9CJPfUFzgLqIMqCF.png" /></figure><ul><li><strong>Apache Kafka</strong>: A distributed streaming platform capable of handling trillions of events a day. Kafka enables real-time data feeds and is often used for building high-performance data pipelines, streaming analytics, and integrating data systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*NmrLlmrsnt5Q6_2X.png" /></figure><ul><li><strong>Google BigQuery</strong>: A fully managed, serverless data warehouse that enables scalable analysis over vast amounts of data. BigQuery is known for its fast SQL queries and ease of integration with other Google Cloud services.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*CumuxttiKLjzqzGC.png" /></figure><h3><strong>A Hands-on Example: ETL Pipeline for Movie Streaming Data</strong></h3><p>In this example, we’ll create a simplified ETL pipeline that simulates extracting movie streaming logs from Kafka, transforms the data to assign ratings based on viewing duration, and loads the transformed data into Google BigQuery for analysis.</p><p>Before we dive into the details of our ETL process, let’s first understand the backbone of our workflow orchestration in Apache Airflow: the Directed Acyclic Graph, or DAG. In Airflow, a DAG is a collection of all the tasks you want to run, organized in a way that reflects their relationships and dependencies.</p><p>In our movie streaming data scenario, the DAG will orchestrate three primary tasks corresponding to the key phases of an ETL pipeline:</p><ul><li>Extracting data from Kafka</li><li>Transforming our data with a Python function (Pandas is used here)</li><li>Loading the processed data into Google BigQuery</li></ul><p>By defining these tasks within a DAG, we can ensure they are executed in the correct order and with the necessary dependencies respected.</p><pre># All packages required:<br>from datetime import datetime, timedelta<br>from airflow.models.dag import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.operators.bash_operator import BashOperator<br>import pandas as pd<br>from kafka import KafkaConsumer<br>from tqdm import tqdm<br>import re<br>import gc<br>from google.cloud import bigquery<br><br># DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;email&#39;: [&#39;mingweig99@gmail.com&#39;],<br>    &#39;email_on_failure&#39;: False,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br>with DAG(<br>    &#39;kafka_extraction_dag&#39;,<br>    default_args=default_args,<br>    description=&#39;Kafka ETL DAG&#39;,<br>    schedule_interval=timedelta(days=1),<br>    start_date=datetime(2023, 1, 1),<br>    catchup=False,<br>) as dag:<br>(<br># E, T, L<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zID9MdYABFaLN7zoYPdjmg.png" /><figcaption>DAGs Overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNe7p6Ue55cFEaiwnD73jQ.png" /><figcaption>Full ETL Pipeline</figcaption></figure><p><strong>Extract Data from Kafka</strong></p><p>Our pipeline starts by extracting streaming log data from Kafka. Each log entry includes a timestamp, user ID, and the requested movie ID.</p><pre> def extract_kafka_data(**kwargs):<br>        ti = kwargs[&#39;ti&#39;]<br>        consumer = KafkaConsumer(<br>            &#39;movielog12&#39;,<br>            bootstrap_servers=[&#39;localhost:9092&#39;],<br>            auto_offset_reset=&#39;latest&#39;,<br>            group_id=&#39;team12_m2&#39;,<br>            consumer_timeout_ms=5000 <br>        )<br><br>        # Collect 10 seconds of data<br>        end_time = datetime.now() + timedelta(seconds=10)<br>        data = []<br>        while datetime.now() &lt; end_time:<br>            for message in consumer:<br>                decoded_message = message.value.decode(&#39;utf-8&#39;)<br>                data.append(decoded_message)<br>                if datetime.now() &gt;= end_time:<br>                    break<br>        <br>        print(f&quot;Extracted {len(data)} records from Kafka.&quot;)<br>        # push this data to XCom for the next task or save it somewhere<br>        ti.xcom_push(key=&#39;data&#39;, value=data)<br><br>        # Don&#39;t forget to close the consumer<br>        consumer.close()<br>    # Airflow PythonOperator<br>    extract_task = PythonOperator(<br>        task_id=&#39;extract_kafka_data&#39;,<br>        python_callable=extract_kafka_data,<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*llWfKB_EI3418VLs4tEKCQ.png" /><figcaption>Extract pipeline</figcaption></figure><p><strong>Transform Data with Python</strong></p><p>After extraction, we perform a transformation on the data. In this stage, we calculate a hypothetical rating based on a toy function: the duration a user spends watching a movie.</p><pre> def transform_data(**kwargs):<br>        <br>        def assign_rating(minute):<br><br>            if minute &gt;= 130:<br>                return 5<br>            elif minute &gt;= 100:<br>                return 4<br>            elif minute &gt;= 75:<br>                return 3<br>            elif minute &gt;= 30:<br>                return 2<br>            else:<br>                return 1<br><br>        ti = kwargs[&#39;ti&#39;]<br>        # load extracted data from extract_kafka_data<br>        data_extracted = ti.xcom_pull(task_ids=&#39;extract_kafka_data&#39;, key=&#39;data&#39;)<br>        print(f&quot;Transforming {len(data_extracted)} records...&quot;)<br>        # Split each string into a list of values<br><br>        # ........ bunchs of transform codes ..........<br><br>        print(f&#39;Transformed data with {len(merged_data)} records...&#39;)<br><br>        ti.xcom_push(key=&#39;transformed_data&#39;, value=merged_data)<br>    <br># Airflow PythonOperator<br>    transform_task = PythonOperator(<br>        task_id=&#39;transform_data&#39;,<br>        python_callable=transform_data,<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*wtQdErfVMCNyrsvtVIFuMw.png" /><figcaption>transform pipeline</figcaption></figure><p><strong>Load Data into Google BigQuery</strong></p><p>Finally, the transformed data is loaded into Google BigQuery, where it can be queried and analyzed.<br>This approach splits the loading process into two steps to enhance modularity and flexibility. First, transformed data is saved to a CSV file, allowing inspection or modification before loading. Then, an external script (bigquery_load.py) is called to perform the data load into BigQuery, decoupling data preparation from the loading logic and enabling more complex processing/error handling in the external script.</p><pre>def load_data_ext(**kwargs):<br>        ti = kwargs[&#39;ti&#39;]<br>        transformed_data = ti.xcom_pull(task_ids=&#39;transform_data&#39;, key=&#39;transformed_data&#39;)<br>        csv_path = &#39;/transformed_data.csv&#39;<br>        transformed_data.to_csv(csv_path, index=False)<br>    <br>    load_task_ext = PythonOperator(<br>        task_id=&#39;load_data_ext&#39;,<br>        python_callable=load_data_ext,<br>    )<br>    <br>    run_external_load_script = BashOperator(<br>        task_id=&#39;run_external_load_script&#39;,<br>        bash_command=&#39;python /bigquery_load.py&#39;,<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*D2VqACIoatR8rngeSqxgwQ.png" /><figcaption>Load pipeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55y2dtFI7CvNUUfaIUvKjA.png" /><figcaption>Results of loaded Big Query Table</figcaption></figure><h3>Strengths</h3><p>This approach capitalizes on the unique strengths of each tool to create a robust ETL pipeline:</p><ul><li><strong>Apache Airflow’s Workflow Orchestration</strong>: Airflow offers a visual interface for monitoring and managing workflows, ensuring tasks run in order and on schedule. Its programmable nature allows for dynamic pipeline generation, scalability, and integration with a wide range of data sources and services.</li><li><strong>Google BigQuery’s Powerful Analytics Engin</strong>e: BigQuery allows for the storage and analysis of large datasets within seconds. Its serverless architecture means that it can scale automatically to meet the demands of querying large datasets, facilitating rapid insights and decision-making.</li><li><strong>Efficient Pipeline to Modeling</strong>: Integrating Apache Airflow with Google BigQuery streamlines the path from data processing to modeling. By orchestrating workflows that automate data preparation and leverage BigQuery’s analytics, teams can swiftly transition to the modeling stage, accelerating the delivery of actionable insights and predictive models.</li></ul><h3>Limitations</h3><p>While this integrated approach offers powerful capabilities for ETL processes, it also comes with its own set of challenges:</p><ul><li><strong>Complexity in Setup and Management:</strong> Configuring and maintaining a pipeline that involves multiple sophisticated tools like Apache Airflow, Kafka, and BigQuery requires a good understanding of each platform. The initial setup can be time-consuming and complex, especially for those new to these technologies.</li><li><strong>Monitoring Across Different Components</strong>: Ensuring seamless data flow across different components of the pipeline necessitates comprehensive monitoring and debugging strategies. Each tool has its own monitoring solutions, and integrating these can sometimes introduce complexity in ensuring end-to-end visibility.</li></ul><h3>Conclusion</h3><p>Building an ETL pipeline with Apache Airflow, Kafka, and Google BigQuery demonstrates how these tools can be combined to facilitate a robust data processing workflow. By automating the extraction, transformation, and loading phases, data scientists and engineers can focus more on deriving insights through modeling/visualizing data and less on the mechanics of data management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1436081c5943" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>