<?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[Seatfrog - Medium]]></title>
        <description><![CDATA[Every journey beyond the ordinary - Medium]]></description>
        <link>https://medium.com/seatfrog?source=rss----7802c5a017c1---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Seatfrog - Medium</title>
            <link>https://medium.com/seatfrog?source=rss----7802c5a017c1---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:41:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/seatfrog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWS Data Pipeline with Airflow]]></title>
            <link>https://medium.com/seatfrog/aws-data-pipeline-with-airflow-410488af5009?source=rss----7802c5a017c1---4</link>
            <guid isPermaLink="false">https://medium.com/p/410488af5009</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Raquel Vaz, PhD]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 13:54:00 GMT</pubDate>
            <atom:updated>2020-10-09T14:42:19.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5u9H3QLyp9vnaqffnOd4A.png" /></figure><p>At <a href="https://seatfrog.com/?utm_source=medium&amp;utm_medium=blog&amp;utm_campaign=aws_data_pipeline_with_airflow">Seatfrog</a> we continuously research new technologies to find the best solutions to tackle our challenges. That means when we add a new technology to our stack that might result in many research hours spread across many different sources. This motivated us to share with everyone the key learnings we wish we had known when we started using Apache Airflow.</p><p>Building an ETL process is the first step to deploy any Data Science project. For that reason it is important that Data Scientists are empowered with the right tools so they can own a project from beginning to end.</p><p><strong>Who are you?</strong> This post is aimed at Data Scientists that are getting started with Airflow and ETL workflows.</p><p>In this tutorial we are going to build a data pipeline using Apache Airflow on AWS. This pipeline automates the process of ingesting files from an S3 bucket into a MySQL database.</p><p>We will implement a simple architecture to keep things short (proof of concept style), but we will cover all the key aspects of this pipeline for completeness. At the end we have code snippets that were not in our core example, but we found them useful when the team was researching and implementing things at Seatfrog.</p><h3>What are we trying to build?</h3><p>Imagine one of the data sources you need for your new ML project is currently stored in files kept in an S3 bucket. A new file lands there every day. Ideally you would like to ingest all files into a database to build an application on top. You would like this to happen every day, so your database is up-to-date.</p><p>If you go to the Apache Airflow project <a href="https://airflow.apache.org/">website</a> you will find the following description:</p><p>“Airflow is a platform created by the community to programmatically author, schedule and monitor workflows.”</p><p>This is achieved through a Directed Acyclic Graph (DAG) which describes the relationships and dependencies of the tasks we wish to execute. This is defined with a Python script.</p><p>To accomplish what we set ourselves to do, we are going to create two tasks, one to figure out which files from the bucket need to be processed, and another to do the required transformations and ingest them into a MySQL database. In this tutorial we used Apache Airflow version : <a href="https://pypi.python.org/pypi/apache-airflow/1.10.4">1.10.4</a>.</p><h4>The UI</h4><p>Airflow has a UI that displays all of our DAGs, active and inactive — you will have to switch the toggle to “ON” to activate it or your workflow or it will not Run. You can also use the UI to monitor tasks and check the logs, create variables and connections. We will go into a bit more detail below on the latter.</p><h4>Connections</h4><p>Before we move on to the implementation we need to setup our connections in Airflow. Once those are defined we can use Airflow Hooks to securely retrieve them. This tutorial requires a MySQL connection and an S3 connection. Airflow has native operators for both connection types. These can be setup in the Airflow UI. Simply go to Admin → Connections. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZ4KWHRynCucsGxSp4E_wg.png" /><figcaption>Airflow UI — setup connections.</figcaption></figure><p>There you can create or edit your connections. For the MySQL connection you need the following fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VY3KqR0qH_zT7uV85pz0uw.png" /><figcaption>Fields required to setup a MySQL connection.</figcaption></figure><p>For the S3 connection you should fill in the fields below, where the password is your AWS_SECRET_ACCESS_KEY.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*HGY3n4eQQKmAYfaM4J5avQ.png" /><figcaption>Fields required to setup an S3 connection.</figcaption></figure><p>For the remainder of the tutorial we will assume that there is a connection to S3 with the connection id “s3_connection” and another to a MySQL database with connection id “mysql_connection”.</p><h3>Implementation</h3><p>In Airflow an operator represents a task. They determine what is going to be executed when the task is triggered.</p><p>We will use Airflow’s native operator PythonOperator for both tasks. This operator receives as argument a Python function that it executes when the task is triggered.</p><p>Our code uses common Python packages such as pandas, boto3 to interact with AWS, and sqlalchemy to connect to the database.</p><p>The code to define the DAG, tasks and task dependencies is below. The functions files_to_process and process_files are showed and explained further down. To keep things clean and easy to understand we explain each part of the code separately.</p><pre>from airflow.models import DAG<br>from airflow.operators import PythonOperator<br>from airflow.utils.dates import days_ago<br><br>args = {<br>&#39;owner&#39;: &#39;me&#39;,<br>&#39;description&#39;: &#39;my_pipeline&#39;,<br>&#39;start_date&#39;: days_ago(1)<br>}<br><br>dag = DAG(dag_id=&#39;my_pipeline&#39;,<br>default_args=args,<br>schedule_interval=&#39;@daily&#39;<br>)<br><br># task to list files for ingestion<br>get_list = PythonOperator(task_id=&#39;get_list&#39;,<br>python_callable=files_to_process,<br>dag=dag)<br><br># task to batch process files from previous task<br>process_files = PythonOperator(task_id=&#39;process_files&#39;,<br>provide_context=True,<br>python_callable=process_files,<br>dag=dag)<br><br># task dependencies<br>get_list &gt;&gt; process_files</pre><p>The first DAG Run is created based on the minimum start_date for the tasks in our DAG, in this case we set it to one day ago to guarantee it is triggered at least once. Subsequent Runs will be created by the parameter schedule_interval. In the example, @daily means it will run every day at midnight. It can be set as a cron expression, more information <a href="https://airflow.readthedocs.io/en/latest/dag-run.html">here</a>.</p><p>In Airflow, tasks are meant to be isolated pieces of work, so by default there is no access to the data from the current to the subsequent task. Nonetheless, we might need to pass some messages to downstream tasks. To achieve this we can use cross-communication (<a href="https://airflow.apache.org/docs/stable/concepts.html?highlight=xcom#concepts-xcom">XCom</a>).</p><p>The second task process_files, has provide_context=True to enable XCom from the upstream task get_list.</p><p>In order to run our DAG we will need the following Python packages:</p><pre>import pandas as pd</pre><pre>import boto3                                     # AWS <br>from sqlalchemy import create_engine             # MySQL connection</pre><pre>from airflow.hooks.mysql_hook import MySqlHook   # MySQL Hook<br>from airflow.hooks.S3_hook    import S3Hook      # S3 Hook</pre><p>Below we take a look at the specific Python functions we wish to trigger.</p><h3>Files to process</h3><p>We want our workflow to process each file only once. There are many ways to do so, having adequate monitoring as files move through different steps of the ETL process is essential for reproducibility and reliability. However, discussing those details and best practices is outside the scope of this tutorial. As such, for this proof of concept style implementation, we will simply keep track of the files that we have processed by adding a column in our MySQL table with the source filename. This way we have our data linked to the original file we extracted it from.</p><p>When our first task is triggered it will query the database to find all filenames that have been ingested and compare them with all files listed under a specific bucket+prefix in S3. The result will be a list of files that have not yet been processed and this will be passed downstream using cross-communication.</p><p>The Python functions to achieve this are defined below.</p><pre># function to retrieve filenames from an s3 bucket <br>def get_list_from_s3(my_bucket,my_prefix):<br>  filenames = []<br>  bucket_obj = S3Hook(&#39;s3_connection&#39;).get_bucket(my_bucket)<br>  for obj in bucket_obj.objects.filter(Prefix=my_prefix):<br>    path, filename = os.path.split(obj.key)<br>    filenames.append(filename)</pre><pre>  return filenames</pre><pre># function to retrieve filenames from a MySQL database<br>def get_list_from_mysql():<br>  # mysql connection <br>  conn_str_app = MySqlHook(&#39;mysql_connection&#39;).get_uri()<br>  engine_app = create_engine(conn_str_app, echo=False)<br> <br>  # find ingested files<br>  qry=&quot;&quot;&quot;<br>      SELECT <br>        filename<br>      FROM MyTable <br>      &quot;&quot;&quot;<br>  df = pd.read_sql_query(qry, engine_app)<br>  already_processed = df[&#39;filename&#39;].tolist()</pre><pre>  return already_processed</pre><pre>def files_to_process():<br>  # find all files from given bucket with a specific prefix<br>  filenames = get_list_from_s3(my_bucket,my_prefix)</pre><pre>  # find all files that already have been stored in MySQL<br>  already_processed = get_list_from_mysql()</pre><pre>  # find the difference between processed and to process files<br>  set_all_files = set(filenames)<br>  set_processed = set(already_processed)</pre><pre>  to_process = set_all_files.difference(set_processed)<br>  files_to_process = list(to_process)<br> <br>  # returns a list of the files we wish to process in the next task<br>  return files_to_process</pre><h3>Ingest files</h3><p>Once the task that finds the list of files to ingest is completed, our next task is triggered automatically by Airflow. This task will loop through all files, implement all required transformations and ingest them on a one-by-one basis into the database.</p><pre>def process_files(**context):<br>  # retrieve using xcomm the result from the previous task<br>  files_to_process =     context[&#39;task_instance&#39;].xcom_pull(dag_id=&#39;my_pipeline&#39;,task_ids=&#39;get_list&#39;)<br>  <br>  # check if there&#39;s at least one file to ingest<br>  if len(files_to_process) &gt;= 1:<br>    # loop through all files<br>    for filename in files_to_process:<br>      s3 = S3Hook(&#39;s3_connection&#39;).get_conn()<br>      obj = s3.get_object(Bucket=my_bucket, Key= my_prefix+filename)<br>      data = pd.read_csv(obj[&#39;Body&#39;]) # &#39;Body&#39; is a key word</pre><pre>      # transform file add column with filename<br>      data[&#39;filename&#39;] = filename</pre><pre>      # here would be the place to add data transformations<br>      # so that your DataFrame matches your data model in MySQL</pre><pre>      # mysql connection <br>      conn_str_app = MySqlHook(&#39;mysql_connection&#39;).get_uri()<br>      engine_app = create_engine(conn_str_app, echo=False)<br>      # save to MySQL<br>      data.to_sql(&#39;MyTable&#39;, con=engine_app, if_exists=&#39;append&#39;, index=False)</pre><h3>What have we accomplished?</h3><p>We have described all the necessary steps to setup an automated workflow to ingest files in AWS to a MySQL database with Airflow.</p><p>Once we get to this point we are ready to start building our machine learning applications on top. Airflow can be used to schedule model training and predictions too. As you gain knowledge of the basic building blocks of Airflow you can start designing more complex workflows.</p><h3>Other things to consider</h3><p>Something we have not discussed is how to make your custom operators, for example, if there are tasks you wish to execute across multiple workflows, you could consider writing your own operator (usually starting from inheriting from a native Airflow operator) and add the functionality you need. As an example, you could have an operator that abstracts the logic of retrieving and processing multiple files. The only custom part is which specific set of transformations (feature engineering, modify date formats, etc.) you wish to apply to your data before inserting it into your MySQL table.</p><h3>Code snippets</h3><p>Finally, as we mentioned at the start, we are going to share some code snippets that we found ourselves using all the time in ETL tasks.</p><p>Extract a date from a filename using regex and save it as a string in the format we wish. In the example below, we have a date as part of the filename string in the format ‘YYYYmmdd’ and we wish to extract this and transform into a string with the format ‘YYYY-mm-dd’.</p><pre>import re<br>from datetime import datetime</pre><pre>m = re.search(&quot;([0-9]{8})&quot;, filename)<br>capture = m.group(1)<br>date = datetime.strptime(capture, &#39;%Y%m%d&#39;)<br>date_str = date.strftime(&quot;%Y-%m-%d&quot;)</pre><p>Saving a DataFrame in a specific format in S3. This example uses .avro, but this code can be easily adapted to a .csv (replace BytesIO with StringIO).</p><pre>from io import BytesIO<br>import pandavro as pdx</pre><pre>s3 = AwsHook(aws_conn_id=&#39;s3_connection&#39;).get_session().resource(&#39;s3&#39;)</pre><pre>avro_buffer = BytesIO()<br>pdx.to_avro(avro_buffer, df)<br>   <br>s3.Object(my_bucket, my_key).put(Body=avro_buffer.getvalue())</pre><p>That’s it, hope you found this useful. Have fun creating workflows! 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=410488af5009" width="1" height="1" alt=""><hr><p><a href="https://medium.com/seatfrog/aws-data-pipeline-with-airflow-410488af5009">AWS Data Pipeline with Airflow</a> was originally published in <a href="https://medium.com/seatfrog">Seatfrog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>