<?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 Angela Niederberger on Medium]]></title>
        <description><![CDATA[Stories by Angela Niederberger on Medium]]></description>
        <link>https://medium.com/@angelaniederberger?source=rss-c643a2defe9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tul7_zlxm3VpEh5_0Txn3Q.jpeg</url>
            <title>Stories by Angela Niederberger on Medium</title>
            <link>https://medium.com/@angelaniederberger?source=rss-c643a2defe9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:48:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@angelaniederberger/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 an End-to-End Data Pipeline in the Google Cloud]]></title>
            <link>https://levelup.gitconnected.com/building-an-end-to-end-data-pipeline-in-the-google-cloud-4ae46536ea6a?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae46536ea6a</guid>
            <category><![CDATA[kestra]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 03:32:48 GMT</pubDate>
            <atom:updated>2025-06-07T20:42:50.016Z</atom:updated>
            <content:encoded><![CDATA[<h4>Step by Step Guide for Simple Data Extraction, Loading, Transformation and Visualization</h4><figure><img alt="A cat with big green eyes looks into the camera very attentively." src="https://cdn-images-1.medium.com/max/1024/0*wRIH1pTFcIQQ7K5O" /><figcaption>Photo by <a href="https://unsplash.com/@caleb_woods?utm_source=medium&amp;utm_medium=referral">Caleb Woods</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Table of Contents</h4><ol><li><a href="#72fc">Introduction</a></li><li><a href="#3771">Project Overview</a><br>Problem Statement<br>Pipeline Architecture<br>Prerequisites</li><li><a href="#c14e">Data Extraction and Loading</a><br>Docker<br>Kestra<br>Virtual Machine</li><li><a href="#09b1">Data Modeling</a><br>Kimball’s Dimensional Modeling<br>Dataform</li><li><a href="#caf4">Visualization and Reporting</a><br>Looker Studio</li><li><a href="#72d1">Conclusion</a></li></ol><h3>Introduction</h3><p>In this article, I will show you how I built a batch data pipeline that automatically updates daily, leveraging modern cloud and containerization technologies. I developed this end-to-end data pipeline as my final submission for the <a href="https://github.com/DataTalksClub/data-engineering-zoomcamp">Data Engineering Zoomcamp</a> (cohort 2025). The data used consists of air quality measurements in the City of Zurich, Switzerland, and is provided by the city government with an open source Creative Commons License (cc-zero).</p><p>I utilized the following technologies:</p><ul><li><a href="https://www.docker.com/"><strong>Docker</strong></a><strong> &amp; </strong><a href="https://docs.docker.com/compose/"><strong>Docker Compose</strong></a>: For containerization and orchestration</li><li><a href="https://cloud.google.com/products/compute?hl=en"><strong>Google Compute Engine</strong></a><strong> (Virtual Machine) with Scheduling</strong>: To run automated data workflows</li><li><a href="https://kestra.io/"><strong>Kestra</strong></a>: Orchestrating workflows in a scalable manner</li><li><a href="https://cloud.google.com/storage?hl=en"><strong>Google Cloud Storage</strong></a>: Storing raw data files</li><li><a href="https://cloud.google.com/bigquery?hl=en"><strong>BigQuery</strong></a>: Cloud-based data warehouse for storing and querying data</li><li><a href="https://cloud.google.com/dataform?hl=en"><strong>Dataform</strong></a>: Automated data transformations (modeling) in BigQuery</li><li><a href="https://cloud.google.com/looker-studio?hl=en"><strong>Looker Studio</strong></a>: Creating visualizations and reports</li><li><a href="https://github.com/"><strong>GitHub</strong></a>: Version control and project management</li></ul><p>I will explain how I used each of these tools in the sections below, but first I want to give an overview of the project as a whole.</p><h3>Project Overview</h3><figure><img alt="A view over a city with a lot of smog." src="https://cdn-images-1.medium.com/max/1024/0*XQ4GAWAVFPu6O6e4" /><figcaption>Photo by <a href="https://unsplash.com/@callmefred?utm_source=medium&amp;utm_medium=referral">Call Me Fred</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Problem Statement</h4><p>Air pollution is a serious public health issue in many cities around the world. I discovered years ago that my city publishes all of its measurements of air pollutants, but I didn’t know how to make sense of this data. I wanted to create a visualization that gives a clear indication of how serious a certain level of pollution is, for each independent pollutant, and which also explains what this pollutant does.</p><p>Therefore, I generated a dataset that contains the <strong>pollution measurements</strong>, but also the<strong> measurement location, emission limits</strong> and <strong>descriptions</strong> for each pollutant. For the visualization I then chose to calculate how many days in a year the pollution was higher than it should have been. This gives an intuitive understanding of how damaging the situation is.</p><h4>Pipeline Architecture</h4><p>Here’s an illustration of the different steps in the data pipeline and the tools used to complete each one:</p><figure><img alt="The data flows from data files into Kestra (inside a Docker container running in a virtual machine) and from there into Google Cloud Storage, then via Kestra into BigQuery. In BigQuery it is transformed through Dataform and then displayed in Looker Studio." src="https://cdn-images-1.medium.com/max/1024/1*rzAeffU2HjTIO3lmh2n6ZA.png" /><figcaption>Pipeline Architecture (Image by the Author)</figcaption></figure><p>In the following sections you can find detailed information on how each of these steps was implemented and how much it costs.</p><h4>Prerequisites</h4><p>If you want to follow along with the pipeline setup, you will require the following tools:</p><ul><li>Docker &amp; Docker Compose</li><li>Google Cloud Platform account with billing enabled</li><li>GitHub account</li></ul><h3>Data Extraction and Loading</h3><p>The <a href="https://data.stadt-zuerich.ch/dataset/ugz_luftschadstoffmessung_tageswerte">raw data files</a> are provided by the City of Zurich in its Open Data Catalog. To extract these automatically, I set up a Docker container with a Kestra image and hosted it in a virtual machine in the Google Cloud. Then I scheduled flows in Kestra to extract the data from the Open Data Catalog, store it in Google Cloud Storage and then load it into BigQuery.</p><h4><strong>Docker</strong></h4><p>I started by spinning up a Docker container with a Kestra image locally to develop and test the flows. I used this <a href="https://github.com/Alessine/zurich_air_quality/blob/main/docker-compose.yml">docker-compose file</a> to get all the different resources running with the command docker-compose up -d. Besides Kestra, the file also specifies a Postgres image. At first, I thought this would not be necessary if I’m writing the data to Google Cloud Storage and BigQuery, but I learned that <strong>without a Postgres image, the setup in Kestra does not persist once I stop the container</strong>.</p><h4><strong>Kestra</strong></h4><p><em>Side note: If you want to get a general introduction to Kestra, please check out this other </em><a href="https://medium.com/@angelaniederberger/learning-in-public-orchestration-with-kestra-0ec485da063e"><em>article</em></a><em> that I wrote while working through the zoomcamp curriculum. There are also lots of basic Kestra tutorials available on their </em><a href="https://www.youtube.com/@kestra-io"><em>YouTube channel</em></a><em>.</em></p><p>Using my local Kestra Docker image, I entered into the Kestra UI, which sits at http://localhost:8080 while you’re working on your local machine. I developed three flows (the Kestra equivalent of DAGs in Airflow):</p><ol><li>to set the key-value pairs for Google Cloud parameters and authentication.</li><li>to extract, save and load the air pollution metrics.</li><li>to extract, prepare, save and load the metadata on air pollutants, emission limits and data collection locations.</li></ol><p>Here are the flows from the Kestra UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*9CYnp3D1TPL72lTQQ1SrMQ.png" /><figcaption>Flows from the Kestra UI (Image by the Author)</figcaption></figure><p>As you can see, in the <a href="https://github.com/Alessine/zurich_air_quality/blob/main/flows/prod/gcp_keyvaluestore.yml">first flow</a> I defined the GCP variables differently depending on whether the flow is executed in development or production mode. <strong>This allowed me to separate the outputs while developing the flows into development buckets and datasets.</strong> The credentials, project ID and location were the same for both, so I excluded them from the if-statement.</p><p>For the air quality metrics (<a href="https://github.com/Alessine/zurich_air_quality/blob/main/flows/prod/load_daily_airquality_data.yml">second flow</a>), which are available in .csv format (<a href="https://github.com/Alessine/zurich_air_quality/blob/main/data/ugz_ogd_air_d1_2025.csv">sample data</a>), the process is relatively simple: the files are downloaded from the Open Data Catalog, saved in a Google Cloud Storage bucket and from there the data gets loaded and merged into one BigQuery table incrementally (day by day).</p><p>However, since the metadata is provided in a nested .json format (<a href="https://github.com/Alessine/zurich_air_quality/blob/main/data/uzg_ogd_metadaten.json">sample data</a>), BigQuery was not able to infer the table schemas automatically. Therefore, in the <a href="https://github.com/Alessine/zurich_air_quality/blob/main/flows/prod/load_airquality_metadata.yml">third flow</a> <strong>I had to add a python transform into the Kestra flow to unnest and store the data in separate </strong><strong>.csv files.</strong> To achieve this, I included the following python script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bb31af4ce1f25f1c25b3a31b6b6f60e/href">https://medium.com/media/1bb31af4ce1f25f1c25b3a31b6b6f60e/href</a></iframe><p>To run a python script in Kestra, you need to define a python image to be used to execute the script in the flow. I went for python:slim, since my script is not very extensive. The transformed .csv files are then uploaded to the storage bucket and loaded into BigQuery tables as snapshot datasets.</p><p>Once I was sure everything is working as intended, I pushed the flows into my GitHub repository, so that I would be able to use them in production later. The datasets created through these Kestra flows are available in BigQuery. You can take a look at them here:</p><ul><li><a href="https://console.cloud.google.com/bigquery?inv=1&amp;invt=AbtiEQ&amp;project=zurich-air-quality&amp;ws=!1m4!1m3!3m2!1szurich-air-quality!2sair_quality_data">air_quality_data</a>: tables as ingested by Kestra in production</li><li><a href="https://console.cloud.google.com/bigquery?inv=1&amp;invt=AbtiEQ&amp;project=zurich-air-quality&amp;ws=!1m4!1m3!3m2!1szurich-air-quality!2sair_quality_data_dev">air_quality_data_dev</a>: tables as ingested by Kestra in development</li></ul><p>You can also see in the image above that flows two and three are associated with a <strong>trigger</strong>, but more on this in the next section.</p><h4><strong>Virtual Machine</strong></h4><p>In order to be able to run the Kestra pipelines productively in the cloud, <strong>I set up a Virtual Machine (VM) in the Google Cloud following this </strong><a href="https://www.youtube.com/watch?v=qwA7-hm7d2o"><strong>guide</strong></a>. I selected a general purpose low-cost E2-medium instance (with two vCPUs and 4 GB of memory), which costs around $33 per month if you keep it running continuously. It runs on an Ubuntu 22.04 operating system.</p><p>I installed Docker and Docker Compose, copied the <a href="https://github.com/Alessine/zurich_air_quality/blob/main/docker-compose.yml">docker-compose file</a> into the machine, set up the firewall rules and ran the command docker-compose up -d to download and spin up the required Docker images inside the VM (all as shown in the guide mentioned above). Then I was able to <strong>access the Kestra UI on the VM’s external IP on port 8080</strong> (since it’s now running in the cloud, you will not find it on http://localhost:8080). In the Kestra UI, I was then able to pull in the flows from GitHub.</p><p>As mentioned before, two of my Kestra flows are associated with a trigger. I set up this trigger so that each flow will run once per day, early in the morning, to fetch the data from the previous day. Since I only have two processes running once a day, <strong>I also set up a schedule in the cloud console to start and stop the VM every day</strong>, aligned with the Kestra schedules (be sure to check that the time zones match):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*v_86IRrqvdsE8rGOzRCjHQ.png" /><figcaption>VM Instance Schedule in the Cloud Console (Image by the Author)</figcaption></figure><p>In addition, <strong>I defined a start-up script to get the Docker images running whenever the VM is started</strong>. Just click on the instance name, then click ‘Edit’ and scroll down until you see the option to add a start-up script. Here’s what mine looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*oPsKUiGGOmWU9H_7WPn93g.png" /><figcaption>VM Startup Script (Image by the Author)</figcaption></figure><p>This VM now runs for 45 minutes every day, early in the morning. When it starts up, it also spins up the Docker setup and waits to run the Kestra flows. Once the flows are done, it shuts back down, saving me a lot of money.</p><p>You can monitor the usage of the VM in the cloud monitoring section. As you can see, in this case it is fine to choose the smallest available instance: <strong>CPU and memory utilisation are nowhere near the VM’s full capacity</strong>. However, if you’re working with larger datasets or more complex flows, you may need a more powerful machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4bOPGKP34-4SjgsJFZAoQ.png" /><figcaption>Monitoring of VM CPU and Memory utilisation (Image by the Author)</figcaption></figure><p>It is also useful to keep an eye on the costs reported in the billing section. As you can see below, <strong>I am currently paying just short of 11 cents per day for the use of this VM</strong> (as opposed to the $33 per month for continuous use).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Tb2m3zgCfFZi70gmGKeJg.png" /><figcaption>Cost Reporting for the VM Services (Image by the Author)</figcaption></figure><p>With the Kestra flows running daily and pushing the raw data into BigQuery datasets, the next step is the data modeling and transformation to prepare the data for reporting and analysis.</p><h3>Data Modeling</h3><h4>Kimball’s Dimensional Modeling</h4><p>For the data modeling stage, I followed the main principles of Kimball’s Dimensional Modeling. You can read more about the core ideas behind it in my other <a href="https://medium.com/@angelaniederberger/learning-in-public-analytics-engineering-and-dbt-6e72358783ed">article</a> about analytics engineering. The most fundamental part however is that data is separated into dimensions (in this case for example measurement locations or the emission limit for a specific pollutant) and facts (the actual measurements). Below is a more complex example from the <a href="https://docs.getdbt.com/blog/kimball-dimensional-model">dbt documentation</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PensvalxLj5p_rWJyHcU8A.png" /><figcaption>Entity Relationship Diagram of a dimensional model (Image taken from the <a href="https://docs.getdbt.com/blog/kimball-dimensional-model">dbt documentation</a>)</figcaption></figure><p>Facts and dimensions can be joined via an identifier into a staging table, which is then used to generate aggregated datasets that contain only the information that is relevant for the reporting. Such a data model is therefore made up of different layers (staging / processing / presentation), of which only the last one should be available to the end-user.</p><p>I decided to use Dataform for the data modeling, since it is native to the Google Cloud and integrates seamlessly with BigQuery.</p><h4><strong>Dataform</strong></h4><p>When you create a repository in Dataform, you have a few options for settings that I find useful. For example, you can choose to add a schema suffix or a table prefix for when you’re executing transformations manually. I decided to use ${workspaceName} as a suffix for the schema (that is the dataset in BigQuery). My development workspace is called transforms_dev, so when I’m executing a workflow manually, the data is written to a dataset called dataform_transforms_dev, while in production, the data is stored in the dataset dataform. <strong>This provides an easy way to separate development from production</strong>, even with multiple people working on the same repository.</p><p>In addition, when you initialize a development workspace, Dataform automatically creates a file called workflow_settings.yaml, where you can set <strong>default values for the project, location and dataset</strong> to write data to (<a href="https://github.com/Alessine/zurich_air_quality/blob/main/workflow_settings.yaml">example file</a>). You can overwrite these defaults later by specifying alternative values in the definition of your data transforms, which can be useful if you want to separate the transformed data into different projects or datasets.</p><p>Dataform offers a <strong>git integration for versioning of the code</strong>. In addition, you can also connect your Dataform repository with GitHub. Either way, Dataform ensures that all changes to the code are versioned and modifications need to be committed and pushed to production.</p><p>With the raw data available in BigQuery, we need to build a data model to transform it into tables specifically designed to fit the reporting needs. In Dataform, the data transformations are written into SQLX files, with basic table configurations at the top. I started by defining my <strong>data sources</strong>, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6706e94b1c9e06dfdbb55639b4d400eb/href">https://medium.com/media/6706e94b1c9e06dfdbb55639b4d400eb/href</a></iframe><p>Since there are four raw data tables that get updated by Kestra daily, I created four such <a href="https://github.com/Alessine/zurich_air_quality/tree/main/definitions/sources">data source files</a> in Dataform. In terms of terminology, the database here refers to the GCP project, the schema is the dataset in this project and the name corresponds to the table name of the existing source table in BigQuery. Once a data source is properly set up in Dataform, you can reference it in transformation scripts using ${ref(&quot;name&quot;)}.</p><p>In my data model, I then defined three types of transformations: a <strong>view</strong>, some<strong> snapshot tables</strong> and some <strong>incremental tables</strong>. Views and snapshot tables are simple in terms of configuration, so I won’t go into detail about how to set them up. You can check out these examples of a <a href="https://github.com/Alessine/zurich_air_quality/blob/main/definitions/staging/limit_dims_clean.sqlx">view</a> and a <a href="https://github.com/Alessine/zurich_air_quality/blob/main/definitions/reporting/days_above_limit.sqlx">snapshot table</a>, if you’re interested.</p><p>For incremental tables, there are a few interesting configuration options available. For example, if the table increments daily (as in my case), it can be useful to end the SQL script with this macro ${when(incremental(), `WHERE date &gt; (SELECT MAX(date) FROM ${self()})`)}. When running incrementally, Dataform then takes the maximum date from the existing table and inserts only rows with a more recent date (to prevent duplicate rows).</p><p>It also makes sense to <strong>partition such tables by date</strong>, and potentially cluster them by other relevant dimensions. These options can be specified in the configuration at the top like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/429b21beb695b9c819f7419726af34fa/href">https://medium.com/media/429b21beb695b9c819f7419726af34fa/href</a></iframe><p>Partitioning and clustering tables improves downstream query performance, especially when working with large datasets (as explained in my <a href="https://medium.com/@angelaniederberger/learning-in-public-data-warehouse-and-bigquery-58ceb162edd4">article about BigQuery</a>). If you want to see the whole script, take a look at this example of an <a href="https://github.com/Alessine/zurich_air_quality/blob/main/definitions/staging/air_quality_staging.sqlx">incremental table definition</a>.</p><p>Below is a screenshot of the compiled graph with all my data sources and transforms, so you can get an <strong>overview of the dependencies</strong> created in the transformation files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5qo4ZH2HLF6cWiA4QwxvQ.png" /><figcaption>Compiled Graph showing the data model in Dataform (Image by the Author)</figcaption></figure><p>The data sources in green are separated into metrics (‘daily_air_quality’) and dimensions (all the ‘metadata’ sources). They are then combined into a staging table, from which the three reporting datasets are created.</p><p>Finally, I had to set up a <strong>schedule</strong> to make sure the data gets updated regularly. Since I know exactly at what time fresh data will usually arrive from Kestra, I just used a CRON schedule in Dataform to trigger the execution. In the Dataform repository, you can find this option under ‘Releases and scheduling’, where you first need to set up a scheduled release (which means that your code will get compiled fresh at a specific time each day). Then you can set up a time-based schedule, where you can choose to execute the whole pipeline or specific transformations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*QoeMmcZ3c04iHE6bBlavSw.png" /><figcaption>Screenshot of the scheduling options in Dataform (Image by the Author).</figcaption></figure><p>However, in a more complex setup, you may not know exactly at what time your data arrives. In this case, you can set up a Pub/Sub trigger in the cloud (for example following this <a href="https://tanelytics.com/trigger-dataform-after-ga4-bigquery-export/">tutorial</a>). This option helped me a lot for certain use cases at work.</p><p>Finally, let’s take a look at the costs incurred by this setup. In the BigQuery Free Tier, Google offers 10 GB of storage and 1 TB of querying per month (without charge). The transformations in Dataform consume around 260 MB per day, or roughly 7.6 GB per month, which is far below the limit of the Free Tier. Similarly, the required amount of Cloud Storage remains far below 1 GB (even though I backfilled data since the year 2020), so there is also no charge for this.</p><p>At this stage, the reporting tables are all available with the required schema and are getting updated regularly. You can check the BigQuery datasets here:</p><ul><li><a href="https://console.cloud.google.com/bigquery?inv=1&amp;invt=AbtiEQ&amp;project=zurich-air-quality&amp;ws=!1m4!1m3!3m2!1szurich-air-quality!2sdataform">dataform</a>: views and tables generated by the dataform model in production</li><li><a href="https://console.cloud.google.com/bigquery?inv=1&amp;invt=AbtiEQ&amp;project=zurich-air-quality&amp;ws=!1m4!1m3!3m2!1szurich-air-quality!2sdataform_transforms_dev">dataform_transforms_dev</a>: views and tables generated by the dataform model in development</li></ul><p>Now we can move on to the reporting setup.</p><h3>Visualization and Reporting</h3><h4>Looker Studio</h4><p>Finally, I connected Looker Studio to BigQuery via Connected Sheets. I introduced this additional step to limit the query costs to a minimum. In the sheet, I scheduled a data extract from BigQuery once per day, which gets billed, but these costs are negligible, because the datasets are aggregated and therefore quite small. The data connection between the sheet and Looker Studio is anyway free, so it doesn’t matter how many people use the dashboard or how often the filters are adjusted.</p><p>Below is a screenshot of the <a href="https://lookerstudio.google.com/u/0/reporting/f96397ee-34dc-4b35-a1e6-bcc93d6708ef/page/tEnnC">dashboard</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*Jm338rpnV3TBi6Vr3qHKiQ.png" /><figcaption>Screenshot showing the Final Version of the Zurich Air Quality Report (Image by the Author)</figcaption></figure><p>If you take a look at the dashboard, you will see that the safe emission limits for the air pollutants are only ever exceeded on a handful of days. We can conclude that the air quality in Zurich is generally good.</p><h3>Conclusion</h3><p>Just to summarize the main points: the data pipeline presented here runs entirely in the Google Cloud and the main technologies used are either open-source or native to the GCP. The data is updated once per day and modeled into reporting datasets, keeping in line with basic data modeling and BigQuery good-practices. The cost of running this pipeline amounts to about $3.50 per month.</p><p>Of course, there are many aspects that could still be improved. For example, it would be very useful to set up data quality checks and get alerted if something is not working as intended. Assertions in Dataform could be a simple way to achieve this.</p><p>Additionally, the current setup is only functional for small data volumes. To scale the workflows, certain adjustments would be necessary. In this case, it would also be beneficial to set up a CI/CD pipeline for future deployments.</p><p>I hope you found this guide useful! I look forward to reading your comments. In case of questions, you can also find me on <a href="https://www.linkedin.com/in/angela-niederberger/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae46536ea6a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-an-end-to-end-data-pipeline-in-the-google-cloud-4ae46536ea6a">Building an End-to-End Data Pipeline in the Google Cloud</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Data Streaming with Kafka and Flink]]></title>
            <link>https://medium.com/@angelaniederberger/learning-in-public-data-streaming-with-kafka-and-flink-5f84629525ee?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f84629525ee</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 15:18:43 GMT</pubDate>
            <atom:updated>2025-03-23T15:18:43.982Z</atom:updated>
            <content:encoded><![CDATA[<h4>Week 6 of the Data Engineering Zoomcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8qfzN8VOecKnOU1_" /><figcaption>Photo by <a href="https://unsplash.com/@mikeanywhere?utm_source=medium&amp;utm_medium=referral">Mike Lewis HeadSmart Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I’m writing this story while following the 2025 live cohort of the <a href="https://datatalks.club/blog/data-engineering-zoomcamp.html"><strong>Data Engineering Zoomcamp</strong></a>. To enhance the learning and grow a professional network, <a href="https://medium.com/u/bd5b4c871c78">Alexey Grigorev</a> and his team encourage a <strong>Learning in Public Approach</strong>, which means sharing my learning with others. In the final week, we covered Streaming with <a href="https://www.redpanda.com/">Redpanda</a> (Kafka) and <a href="https://flink.apache.org/what-is-flink/flink-architecture/">Flink</a>.</p><h3>Data Streaming</h3><p>Stream processing means that each data point (also called event) is sent into the data pipeline and gets processed separately. In terms of setup, <strong>it requires a server that is constantly running</strong>, which picks up the events in real-time, as they are generated. In the most simple form, this could mean that the events are just collected and passed on into a data warehouse, from where they can then be processed in batches. However, in most cases, we would want to perform some processing or aggregation tasks already in the streaming pipeline, in order to make information available as quickly as possible.</p><p>The skills required to set up a streaming pipeline are therefore <strong>more similar to a typical software engineering profile</strong> (rather than data engineering), as it includes tasks such as setting up a server, maintaining an API and so on. In most data teams, streaming is a niche skill, which makes it difficult to maintain streaming pipelines. Imagine if only one person on a team knows how to maintain a pipeline, which is delivering real-time data around the clock, this would put a lot of pressure on one team member and is generally not desirable.</p><h4>Use Cases of Streaming</h4><p>Nonetheless, there are sometimes cases where it is useful to stream data. The main question to ask is:</p><ul><li><strong>What will happen right away when we get this information?</strong></li></ul><p>If the data triggers automated processes, then it may be a good use case for streaming. On the other hand, if a human is looking at the data, in most cases it is sufficient to use mini-batches (for example updating the data every 5 minutes).</p><p>Here are two examples of use cases for streaming:</p><ol><li><strong>Fraud Detection</strong>: Data comes in, if an employee’s laptop was hacked. This triggers an automatic process to limit the damage. This example was given in the course.</li><li><strong>Trading Risk Evaluation</strong>: Financial institutions use data streaming to monitor trading and market data and calculate risk metrics in real-time. If a risk metrics goes off the charts, this automatically triggers alerts.</li><li><strong>Performance Evaluation</strong>: At major news outlets, we track some aspects of the reading behavior of users in real-time. Based on this, the editor decides which articles should be featured, which should be removed from the home page etc. This is an example from my own job.</li></ol><p>In the majority of cases, batch processing is preferred over stream processing, because having data available in real-time does not provide any real added value and batch processing pipelines are far easier to maintain.</p><h3>Kafka and Flink</h3><p>In the course, we experimented with a streaming setup using Redpanda (which is compatible with Kafka) and Flink. Redpanda / Kafka served as the communication channel where the events came in and got queued.</p><blockquote>Kafka is basically a massive fire hose pointed in one direction.</blockquote><p>Then we used Flink for the following:</p><ul><li>read the events from Kafka (with three options: (1) all the events since the first one, (2) only new events coming in, or (3) specifying a timestamp)</li><li>define what to do with these events (transformations), including watermarks (acceptable lateness)</li><li>initiate parallel processes (multiple executors)</li><li>set up checkpoints, so if the pipeline fails, we would be able to re-start it from the last checkpoint.</li><li>pass the result on to a database (in this case PostgreSQL)</li></ul><p>One type of transformation that is typically used on real-time data involves setting up <a href="https://nightlies.apache.org/flink/flink-docs-master/docs/dev/datastream/operators/windows/">time windows</a>, which group multiple events together. Technically, the data stream is infinite, so windows are a good way to split it into finite ‘buckets’. There are many different ways to define a window:</p><ul><li><strong>tumble</strong>: events are grouped into segments within a specified time-period (e.g. cut every minute).</li><li><strong>sliding</strong>: overlapping tumble windows (e.g. 10-minute windows that are shifted every 5 minutes)</li><li><strong>session</strong>: the grouping is defined by the length of the period between two events.</li></ul><p>In the field of Web Analytics, the Session Window is probably the most commonly used type of window. It splits events into buckets based on how much time has passed since the previous event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*0e8MODc_rCJ0kpWeiC9rSQ.png" /><figcaption>Illustration of the Sessionization of events (Screenshot from the Flink Documentation)</figcaption></figure><p>In Google Analytics, for example, the default session gap is defined as 30 minutes. Therefore, if a user remains inactive for half an hour on the website or in the app, the session is considered closed.</p><h3>Conclusion</h3><p>While it was interesting to see how a streaming pipeline works, the most useful part in this module was for me the differentiation between those use cases that justify streaming and those that do not. The understanding that an automated process should be attached to the streaming pipeline really helps to hone in on the added value that real-time data can provide. I am convinced that the great majority of data problems can (and should) be solved with batch pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f84629525ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Batch Processing and Spark]]></title>
            <link>https://medium.com/@angelaniederberger/learning-in-public-batch-processing-and-spark-ec7e48addf8a?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec7e48addf8a</guid>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 19:42:42 GMT</pubDate>
            <atom:updated>2025-03-12T10:13:50.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>Week 5 of the Data Engineering Zoomcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yb2uBaRPJrtNs9eq" /><figcaption>Photo by <a href="https://unsplash.com/@benharritt?utm_source=medium&amp;utm_medium=referral">Ben Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I’m writing this story while following the 2025 live cohort of the <a href="https://datatalks.club/blog/data-engineering-zoomcamp.html"><strong>Data Engineering Zoomcamp</strong></a>. To enhance the learning and grow a professional network, <a href="https://medium.com/u/bd5b4c871c78">Alexey Grigorev</a> and his team encourage a <strong>Learning in Public Approach</strong>, which means sharing my learning with others. This week, we learned about Batch Processing and Spark.</p><h3>Batch Processing</h3><p>Batch Processing means that the changes and transformations, which need to be applied to a data point, are performed on chunks of data, rather than on individual data points. In practice, it means that all the data for a specific period of time (e.g. daily or hourly) is collected and processed once the relevant time period is over. It is the opposite of Stream Processing, where each data point gets processed as soon as it is created.</p><h4>Technologies</h4><p>There are many technologies that are suitable for processing data in batches. Here are the most common ones:</p><ul><li>Python scripts</li><li>SQL</li><li>Spark</li><li>Flink</li></ul><h4>Why (not) to choose Batch Processing</h4><p>The main advantage of processing data in batches is that batch pipelines are <strong>easier to manage</strong>. Since the data is collected in one place before it is processed, <strong>it’s possible to retry</strong>, if the processing fails. Further, the processing is less time-critical, since the data is by default not available in (almost) real-time. It is also much <strong>easier to scale up</strong> batch processing pipelines, because it is only a question of adjusting the processing power to the size of the data chunks.</p><p>The biggest disadvantage of batch processing is that the <strong>stakeholders need to wait until the specified time period is over</strong>, before the data becomes available for processing. It is therefore not possible to react to new developments etc. in real time. However, the advantages of batch processing often outweigh the disadvantages.</p><h3>Apache Spark</h3><p><strong>Apache Spark is an open-source unified analytics engine for large-scale data processing.</strong> It works in clusters (so jobs can be distributed and happen at the same time) and can be used for both batch and stream processing. It’s a multi-language distributed computing framework, which supports for example Java, Scala, Python (PySpark) and R.</p><h4>When should you use Spark?</h4><p>Spark is a good choice when the data is large and is stored in a data lake in the cloud (typically in <a href="https://en.wikipedia.org/wiki/Apache_Parquet">parquet format</a>). Spark can then be used to turn these files into a database. Spark offers functionality that goes beyond SQL in terms of complexity and for example also supports unit tests. Additionally, it is also good for performing Machine Learning tasks.</p><h4><strong>Spark Cluster: Multiple Executors</strong></h4><p>A Spark cluster typically requires the following entities:</p><ul><li>a Driver: e.g. the laptop where tasks are generated</li><li>the Master: the machine that coordinates all the executors</li><li>Executors: the machines where the tasks are carried out</li><li>Storage: where the data is pulled from and/or written to</li></ul><p>Normally, only the driver is local. Everything else is located in the cloud, in a data center somewhere.</p><p>Spark divides each task into many sub-tasks which are then distributed over multiple executors. Therefore, for example when loading data, it is better to have multiple files, rather than one really large one. In Spark, we avoid putting all the load on one executor by creating partitions (which can either be based on certain columns or just random splits of the dataset).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*li5fN9-X8N0vsLf0BhYUAg.png" /><figcaption>Cloud Storage Files and Spark Clusters (Screenshot from a Presentation by Alexey Grigorev)</figcaption></figure><h4>Running Spark via spark-submit</h4><p>The setup of a Spark cluster can be automated with the spark-submit command. A <a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_5/250305_spark_google_cloud.py">python script</a> including some arguments parsed from the command line can be executed by the cluster as follows:</p><pre>URL=&quot;spark://angela-HP-PC:7077&quot;<br><br>spark-submit \<br>    --master=&quot;${URL}&quot; \<br>    250305_spark_google_cloud.py \<br>        --input_green=./data/pq/green/2021/*/ \<br>        --input_yellow=./data/pq/yellow/2021/*/ \<br>        --output=./data/report-2021</pre><p>For more information on this option, check the <a href="https://spark.apache.org/docs/latest/submitting-applications.html">Spark documentation</a>.</p><h4>Spark Master UI</h4><p>When running Spark jobs, it is possible to survey their execution in the Master UI, which is usually located in the browser at localhost:4040.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*4-ksHvG04kCa4f2PbmGtug.png" /><figcaption>Spark Master UI (Image by the Author)</figcaption></figure><p>This is especially helpful when running more complicated tasks. Two such examples would be GROUP BY and JOIN .</p><h4><strong>Spark Group By</strong></h4><p>Since Spark reads the data from partitioned files, it is necessary to perform the grouping in stages. One executor alone only has access to one part of the data, so there needs to be some sort of exchange between the executors in order to perform the grouping over the entire dataset. This happens in two stages:</p><p>In <strong>stage 1</strong> executors do:</p><ul><li>filtering</li><li>initial group by (one partition at a time)</li><li>output temporary files with intermediate results</li></ul><p>In <strong>stage 2</strong>: reshuffling (algorithm: external merge sort)</p><ul><li>shuffle the results by grouping key, so that the intermediate results for one group are all in the same partition</li><li>second group by in each partition to combine the results from the different executors in stage 1</li></ul><p>In the Spark Master UI, these stages are visualized as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*r5Tkk4_jf8dx_3_epdEJjg.png" /><figcaption>Group By Job in the Spark Master UI (Image by the Author)</figcaption></figure><p>The most costly part of this process is the reshuffling of the intermediate results between the executors. In order to reduce the need for reshuffling, it can be useful to reduce the size of the files by repartitioning them.</p><h4>Spark Joins</h4><p>Spark joins can be performed in two different ways:</p><p><strong>(1) When joining two large tables</strong>, each table is distributed across multiple executors. In this case, it is also necessary to exchange intermediate results between the executors. Again, this happens in two stages:</p><p>In stage 1:</p><ul><li>executors generate a <strong>key — record pair</strong> in both tables. For example, if the join is based on two columns, such as hour and zone, the key for each record would be hour-zone.</li></ul><p>In stage 2: reshuffling</p><ul><li>bring all the records from both tables that have the same key into one partition.</li><li>after the reshuffling: if there are records from both tables with the same key within one partition, they are joined. For example, partition 1 could have records for green and yellow taxi trips for the key 8am-Manhattan . The join would then look like this: 8am-Manhattan, yellow_record, green_record .</li></ul><p><strong>(2) When joining a small table with a large one</strong>, Spark avoids the reshuffling by doing a <strong>Broadcast Exchange</strong>. This means that the whole small table is passed on to each executor, where it is joined with a partition of the large table. This way, reshuffling is not necessary.</p><h4>Actions vs. Transformations</h4><p>In Spark, not all tasks are executed immediately. Rather, they are divided into ‘<strong>lazy’ transformations</strong> and <strong>‘eager’ actions</strong>.</p><p>Examples of transformations:</p><ul><li>selecting columns</li><li>filtering</li><li>joins</li><li>group by</li></ul><p>Examples of actions:</p><ul><li>show</li><li>take</li><li>head</li></ul><p>Transformations and actions are usually chained together, where the action causes the entire chain to be evaluated.</p><h4>SQL with Spark</h4><p>It is possible to execute SQL queries directly in Spark as follows:</p><pre>df_trips_data.registerTempTable(&#39;trips_data&#39;)<br><br>spark.sql(&quot;&quot;&quot;<br>  SELECT <br>      service_type,<br>      count(1)<br>  FROM <br>      trips_data<br>  GROUP BY<br>      service_type;<br>&quot;&quot;&quot;).show()</pre><p>If the transformation is not too complicated, it is best to use SQL directly. The output of the query can be saved into a Spark Dataframe and written to the data lake, e.g. for reporting. For more complex transformations, pySpark offers a lot more flexibility with many existing functions and the possibility to add new ones.</p><h4>Spark Functions and User-defined Functions</h4><p>By simply importing the pre-defined functions ( from pyspark.sql import functions as F ) we get access to a wide range of pre-defined transformations, aggregations, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*wO2I_rzi-ZLNg65tkeGFfQ.png" /><figcaption>List of pySpark pre-defined Functions (Image by the Author)</figcaption></figure><p>In addition, it is also possible to declare any python function as a user-defined pySpark function, which can then also be used for transformations. This way, it is possible to implement non-standard business requirements in a very elegant way.</p><h4>Spark in the Google Cloud</h4><p>Spark offers functionality to interact with a range of Cloud Applications, including the Google Cloud Platform. It is very easy to read and write from Storage Buckets, as well as BigQuery datasets. Spark transformations can also be set up to run in the Google Cloud, by using Dataproc jobs. They can be submitted in the Cloud UI, the command line or via a REST API and are executed in a virtual machine.</p><h3>Conclusion</h3><p>Batch processing is the preferred way of loading and transforming data in the majority of cases, since batch pipelines are easier to manage than streaming pipelines. Spark is one of the most popular frameworks for batch processing, because it can handle very large data volumes and offers a lot of flexibility, by combining the best parts of SQL and Python. It also integrates seamlessly with cloud solutions such as the Google Cloud Platform.</p><p>In my job, I sometimes use pySpark when transforming data in Palantir Foundry. The practical contents of this module are therefore directly applicable to my work. In addition, it is very useful for me to understand a bit more about the internals of Spark, since this allows me to work more efficiently within this framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec7e48addf8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Analytics Engineering and dbt]]></title>
            <link>https://medium.com/@angelaniederberger/learning-in-public-analytics-engineering-and-dbt-6e72358783ed?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e72358783ed</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 20:50:16 GMT</pubDate>
            <atom:updated>2025-03-04T16:46:28.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>Week 4 of the Data Engineering Zoomcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3wctREBsv2tbdoFt" /><figcaption>Photo by <a href="https://unsplash.com/@dtopkin1?utm_source=medium&amp;utm_medium=referral">Dayne Topkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I’m writing this story while following the 2025 live cohort of the <a href="https://datatalks.club/blog/data-engineering-zoomcamp.html"><strong>Data Engineering Zoomcamp</strong></a>. To enhance the learning and grow a professional network, <a href="https://medium.com/u/bd5b4c871c78">Alexey Grigorev</a> and his team encourage a <strong>Learning in Public Approach</strong>, which means sharing my learning with others. In the fourth week, we covered Analytics Engineering and built data models with <a href="https://docs.getdbt.com/">dbt</a>.</p><h3>What is Analytics Engineering?</h3><h4>The Analytics Engineer: the new kid on the block</h4><p>Typically, a data team is required to cover a wide variety of tasks: from loading data into a data lake, to storing it in a structured way in a data warehouse, to then transforming and presenting it in a fashion that delivers value to the business. These tasks are usually divided between multiple roles, with the Data Engineers taking care of the infrastructure and the Data Analysts mining the data to answer questions. <strong>Relatively recently, a new role has emerged: the Analytics Engineer.</strong></p><p>The field of Analytics Engineering sits in between Data Engineering and Data Analysis. The Analytics Engineer is responsible for transforming the data available in the data warehouse into useful and manageable datasets that serve the Data Analysts to answer the relevant business questions. In other words, the Analytics Engineer builds the data model.</p><p>In this role, it is necessary to maintain certain <strong>software engineering practices</strong> (such as versioning the code, etc.), but at the same time the Analytics Engineer needs to have a <strong>sound understanding of the business</strong>. A certain level of technical expertise is required, but most importantly, this person needs to work closely with the business stakeholders. This ensures that the business can drive the development of meaningful data insights.</p><h4>Some background on Data Modeling</h4><p>With the introduction of powerful cloud solutions, data storage has gotten very cheap, while the main costs result from data processing. It therefore makes sense to focus on making data transformations as efficient as possible, while the amount of storage needed for the raw data is less relevant. This has led to a <strong>shift from ETL (extract-transform-load) to ELT (extract-load-transform)</strong>, meaning that data is loaded (and stored) before transforming and cleaning it.</p><p>The transformations that are applied to the data before the business can consume it make up the data model. This includes joining tables, but also performing aggregations and calculating metrics. Data Modeling is especially important when the data volume is large, since it is the main driver of processing costs.</p><h4>Kimball’s Dimensional Modeling</h4><p>In the course, we briefly touched upon <a href="https://www.kimballgroup.com/data-warehouse-business-intelligence-resources/kimball-techniques/dimensional-modeling-techniques/">Kimball’s Dimensional Modeling</a>. The main objectives of this modeling technique are:</p><ul><li>generating understandable data</li><li>maintaining fast query performance</li></ul><p>Redundancies in the data are considered less problematic and normalization of tables is not a goal, since it tends to reduce the performance.</p><p>Tables are organized into staging , processing and presentation layers. In the staging layer, the data is cleaned and prepared. In the processing step, we aggregate tables and add additional metrics. Finally, the presentation step serves to make the data understandable for our stakeholders.</p><p>Presentation tables contain dimensions and facts (while at previous stages these are kept separate). Dimensions describe the business entities while facts contain the measurements and metrics related to business processes. Dimensions and facts need to be joined via a unique identifier.</p><p>Here’s a very simple example from my own business context of digital subscriptions:</p><p><strong>Dimensions</strong>:</p><ul><li>renewal period of the subscription (for example monthly)</li><li>product it gives access to (for example sport premium articles)</li></ul><p><strong>Facts</strong>:</p><ul><li>number of people with an active subscription</li><li>avg. number of days a subscription remains active</li></ul><p>Data models can become exceedingly complex. Luckily, there are many tools available that help keep an overview of all the different transformation steps and to maintain proper software engineering practices. In the course, we worked with dbt Cloud.</p><h3>What is dbt?</h3><p>dbt is a software solution for implementing data transformation workflows in SQL or Python while maintaining software engineering good practices. There is a free open-source option (dbt Core) and a paid enterprise version (dbt Cloud). These are the main features:</p><p><strong>dbt Core:</strong></p><ul><li>open-source, free</li><li>all the transformation functionalities: build and run a dbt project</li><li>SQL compilation logic</li><li>command line interface</li></ul><p><strong>dbt Cloud:</strong></p><ul><li>paid SaaS application, hosted in the cloud</li><li>web-based Integrated Development Environment (IDE) for managing environments, orchestration, schedules, logging &amp; alerting, documentation and more</li><li>administration of multiple roles and users</li><li>transformation workflows with SQL or Python compilation</li><li>support for software engineering best practices (version control, CI/CD, development vs. production deployment)</li></ul><p>A workflow in dbt usually includes the following steps: (1) develop, (2) test, (3) document, (4) deploy. Changes to the code base are versioned and deployed by creating a pull request on GitHub. Projects can be run in Core or Cloud in the same way, but the Cloud solution simplifies these processes a lot by providing an IDE specifically developed for this purpose and by hosting the entire setup.</p><p>In order to get started with your first project in the dbt Cloud, you need:</p><ul><li>a dbt Cloud Developer Account (free for solo developers, but limited in scope).</li><li>a database (e.g. BigQuery) with a service account to establish a connection with dbt.</li><li>a GitHub account to store and deploy the dbt project.</li></ul><h4>Working with dbt</h4><p>dbt provides a template project that needs to be initialized whenever starting a new project. It sets up the default folder structure which, among other things, contains the project setup file (<a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_4/homework/dbt_project.yml">example here</a>). In the screenshot you can see what the cloud IDE looks like, including the most important features:</p><ul><li>version control</li><li>file explorer</li><li>code editor</li><li>data lineage</li><li>buttons for generating a preview of the data, compiling a file or building specific parts of the pipeline.</li><li>command line interface</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJB421FdPLuvPZWa3FeJYA.png" /><figcaption>dbt Cloud IDE (Image by the Author)</figcaption></figure><p>Below are some short descriptions of the most important aspects of data modeling, and how they are managed in dbt.</p><p><strong>Transformations</strong></p><p>The basis for every transformation is the input dataset, which can be either a raw source (meaning a table in the database) or a reference to an output from another transform. The sources are defined in the schema.yml <a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_4/homework/models/staging/schema.yml">file</a>. The transformation steps are then defined in the model, which is simply a .sql file (here’s an <a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_4/homework/models/staging/stg_yellow_tripdata.sql">example</a>). This file is then compiled by dbt to add the Data Definition Language (DDL) steps such as CREATE TABLE or ALTER COLUMN.</p><p><strong>Tests</strong></p><p>Tests can be associated with sources in the schema.yml file, which are then always run when the source is accessed. dbt offers the following out-of-the-box tests on column values:</p><ul><li>unique</li><li>not null</li><li>accepted values</li><li>foreign key to another table</li></ul><p>Custom tests can be defined as queries.</p><p><strong>Materialization</strong></p><p>There are several ways how a table can be materialized by dbt:</p><ul><li>ephemeral (exists only during the run, e.g. a CTE)</li><li>view (virtual table)</li><li>table (physical table, drop and recreate each time)</li><li>incremental table (insert only new data into table)</li></ul><p>The materialization strategy can be defined on an overall level, but also for each model in specific. The closer we are in the model to the consumer, the more likely it is that we want to physically materialize tables to make queries more performant.</p><p><strong>Jinja Macros</strong></p><p>The SQL code in the models is complemented by using Jinja Macros. This allows us to make the code dynamic by creating functions and adding variables or conditional statements. Here are some examples:</p><ul><li>If the variable is_test_run is set to true, then the output will be limited to 300 rows: {% if var(&#39;is_test_run&#39;, default=true) %} limit 300 {% endif %}</li><li>The CTE tripdata is based on the table fhv_tripdata_2019 from the source staging:</li></ul><pre>with<br>    tripdata as (<br>        select *,<br>        from {{ source(&quot;staging&quot;, &quot;fhv_tripdata_2019&quot;) }}<br>        where dispatching_base_num is not null<br>    )</pre><p>When compiling the code, whatever variables, conditions etc. are used in the macros, are applied to generate the code that is then used to build the model.</p><p><strong>Variables</strong></p><p>Variables are defined at the project-level and can be used in macros with {{ var(&#39;...&#39;) }}. They can also be defined in the command line interface (e.g. dbt build --select stg_green_tripdata --vars &#39;{&#39;is_test_run&#39;: false}&#39;) or for specific environments.</p><p><strong>Packages</strong></p><p>A lot of useful dbt packages already exist in the dbt package hub (e.g. dbt_utils). Packages can be imported into different projects by specifying them in the packages.yml file (<a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_4/homework/packages.yml">example here</a>) inside the project. Packages can be used in macros and macros (that is, functions) can also be written into Packages.</p><p><strong>Documentation</strong></p><p>Every single object (models, columns, etc.) can have its own documentation page, which is rendered by dbt as a website after the deployment.</p><h3>Conclusion</h3><p>Analytics Engineering is an essential part of data engineering, connecting the business with the engineering and ensuring that the right kinds of insights are generated from the data available. Overall, dbt Cloud really simplifies the process of modeling raw data and deploying data models into production. It offers support for essential software engineering good practices, the IDE is intuitive and with the project template, it is easy to get started.</p><p>I can see a lot of potential applications for this tool in my work, especially since the volume of online tracking data is huge and the transformation of this raw data is inevitable. With dbt Cloud, it becomes easier to work on a data model in a team, because version control is enforced strictly and changes can only be merged via a pull request. In comparison with the tools available in the Google Cloud (e.g. scheduled queries), this will lead to a far more reliable and stable data infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e72358783ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Data Warehouse and BigQuery]]></title>
            <link>https://medium.com/@angelaniederberger/learning-in-public-data-warehouse-and-bigquery-58ceb162edd4?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ceb162edd4</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 09:40:21 GMT</pubDate>
            <atom:updated>2025-02-12T09:40:21.617Z</atom:updated>
            <content:encoded><![CDATA[<h4>Week 3 of the Data Engineering Zoomcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gNG-6leVMb_-zmKy" /><figcaption>Photo by <a href="https://unsplash.com/@nananadolgo?utm_source=medium&amp;utm_medium=referral">Nana Smirnova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I’m writing this story while following the 2025 live cohort of the <a href="https://datatalks.club/blog/data-engineering-zoomcamp.html"><strong>Data Engineering Zoomcamp</strong></a>. To enhance the learning and grow a professional network, <a href="https://medium.com/u/bd5b4c871c78">Alexey Grigorev</a> and his team encourage a <strong>Learning in Public Approach</strong>, which means sharing my learning with others. The third week was all about Data Warehousing and in particular BigQuery.</p><p>A data warehouse typically consists of different types of data:</p><ul><li><strong>raw data</strong>: coming directly from the source, not having undergone any processing or cleaning</li><li><strong>meta data</strong>: information about the data</li><li><strong>summary data</strong>: transformed data, aggregated, cleaned</li></ul><p>Depending on the use cases of a data warehouse, the data engineers process the raw data to build data marts (collections of summary data), which meet specific requirements.</p><p>Data processing in general can be split into two spheres:</p><ul><li><strong>online transaction processing</strong>: this kind of data processing directly serves and supports business processes, such as e-commerce. It needs to be fast and is therefore kept as slim as possible. It often uses databases, but these usually do not reach the stage of a fleshed out data warehouse.</li><li><strong>online analytics processing</strong>: in this case the processing of data serves the purpose of business intelligence. This often results in a much larger data volume. Information is collected and transformed specifically for the purpose of analysis, without it really being required for the functioning of a business.</li></ul><p>As data engineers, we are typically interested in analytics processing. BigQuery is one of the most common solutions that support large-scale processing as it would be required to build a data warehouse.</p><h3>BigQuery</h3><p>These are some of the main features of BigQuery:</p><ul><li><strong>serverless</strong>: this means there is no infrastructure, servers or database software that needs to be managed</li><li><strong>scalability &amp; availability</strong>: storage and computation capacities are dynamically allocated, so it is possible to scale up these resources very flexibly.</li><li><strong>computation is separate from storage</strong>: the two systems are separate, which allows for very cheap storage and fast processing. Most of the costs are generated by computation.</li><li><strong>storage is columnar</strong>: when querying the data, each column is accessed separately. This improves the performance for aggregations on columns in comparison with record-oriented storage (as for example in a .csv file or in a traditional relational database).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*byKZu9xo4GTHm4C8Pl8OwA.png" /><figcaption>Columnar Storage as shown in the <a href="https://cloud.google.com/blog/topics/developers-practitioners/bigquery-explained-storage-overview">Google Cloud Documentation</a></figcaption></figure><ul><li><strong>built-in features</strong>: BigQuery makes certain processes easier by providing features such as scheduled queries or machine learning.</li></ul><p>Overall, BigQuery is a very powerful and easily scalable solution for a data warehouse, as this <a href="https://cloud.google.com/blog/products/bigquery/anatomy-of-a-bigquery-query">demonstration</a> on the publicly available Wikipedia benchmark dataset shows. The dataset contains 100 billion rows (~7 TB) but the sample query still completes in under 30 seconds, which is indeed impressive.</p><h4>Options for Intelligent Storage</h4><p>There are two possibilities when creating a table: external or materialized (regular). When using an external table, the data is not stored in BigQuery. Instead, it is simply read from files located elsewhere, for example in a Google Cloud Storage Bucket. This reduces the storage cost in BigQuery, but it negatively impacts the query performance.</p><p>Instead, in a materialized table, the data is stored in this table and therefore can be accessed more quickly. When frequently querying a table, it is usually better to create a materialized version of it. The data in either type of table can be partitioned and clustered.</p><p><strong>Partitioning </strong>is especially useful when filtering on the partitioned column. This can drastically improve the query performance and reduce the processing cost. Partitions are often used for date values (for example daily).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*YJT-dzBkougfjyGMFeuTTg.png" /><figcaption>Partitioning as explained in the <a href="https://cloud.google.com/blog/topics/developers-practitioners/bigquery-explained-storage-overview">Google Cloud Documentation</a></figcaption></figure><p>In BigQuery, it is only possible to partition a table on one single column. In total, a table can have a maximum of 4&#39;000 partitions. These partitions can have expiration dates, so they will get deleted automatically. It is also possible to query the metadata of the partitions and see their names, the number of rows in each partition etc.</p><p><strong>Clustering </strong>on the other hand orders the data within partitions. It especially helps to reduce query volume when filtering and ordering data, or when running aggregate queries on clustered columns. It is possible to cluster on up to four different columns. Clustering therefore offers more granularity than partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*dvzx_rEBiaCp2zmJchQm_w.png" /><figcaption>Clustering as explained in the <a href="https://cloud.google.com/blog/topics/developers-practitioners/bigquery-explained-storage-overview">Google Cloud Documentation</a></figcaption></figure><p>Clustering is generally better than partitioning with columns that have high cardinality, since there is no limit for the number of clusters. However, clusters need to be maintained when adding new data to a table. For this purpose, BigQuery performs automatic re-clustering.</p><p>Both partitioning and clustering are most useful when the data reaches a certain volume. As a rule of thumb, it should only be used on tables with more than 1 GB of data.</p><h4>Best Practices for Querying Data</h4><p>These are some simple tips for optimizing queries regarding cost and performance. Many of them reduce cost and improve performance at the same time.</p><p><strong>Cost Reduction</strong></p><ul><li><strong>avoid </strong><strong>SELECT *</strong>: since BigQuery uses columnar storage, queries consume more compute, if columns are selected unnecessarily. This applies to other database systems as well.</li><li><strong>check the price of a query before running</strong>: unlike other tools, in the BigQuery UI, you can see the estimated data volume that will be processed by your query in the top right corner. If you check it regularly, you will develop a sense for how much each query approximately costs.</li><li><strong>partitioning and clustering</strong>: pay attention to how your tables are partitioned and clustered and use this to your advantage, for example by filtering on partitioned columns and aggregating or ordering on clustered columns.</li><li><strong>avoid streaming</strong>: ask yourself if streaming data is really necessary for your use case, since this can quickly get expensive.</li><li><strong>materialize query results</strong> (instead of using WITH statements or CTEs): of course, this does not apply for every single query you run, if you plan to use the results of a query again, materializing them in a table will reduce your costs, since storage is much cheaper than compute.</li></ul><p><strong>Performance Improvement</strong></p><ul><li><strong>filter on partitioned columns</strong>: this reduces the amount of data that is queried in the first place.</li><li><strong>denormalize data</strong>: joins are slow and storage is cheap. Therefore, you can improve your query performance by storing denormalized (combined) tables.</li><li><strong>reduce data before joins</strong>: if you need to do a join, make sure you first reduce the data as much as possible.</li><li><strong>avoid external tables</strong>: reading data from an external source is slow.</li><li><strong>don’t treat </strong><strong>WITH as a prep statement</strong>: again, since storage is cheap, it is usually better to materialize tables for preparation steps that are often repeated.</li><li><strong>don’t shard tables unnecessarily</strong>: sharding means splitting the table into several tables based on some attribute (for example country ). Though sometimes there may be good reasons for doing this, filtering is usually faster than unioning sharded tables back together.</li><li><strong>order last</strong>: ordering is slow, so it is best to perform it once the data has been filtered and aggregated as much as possible.</li></ul><h4>Internal Systems</h4><p>BigQuery uses different systems for storage <strong>(Colossus)</strong> and analysis <strong>(Dremel). </strong>This gives us the best of both:</p><ul><li>with Colossus, storage space is highly scalable</li><li>very fast query execution, since Dremel can separate a query into a query execution tree and execute each node separately.</li></ul><p>However, since the hardware is completely separate, the two systems need to somehow be able to communicate with each other. This is achieved via a <strong>Jupiter</strong> network. The downside is that a reduced network speed can impact the query performance.</p><h3>Conclusion</h3><p>The key things to remember about BigQuery are:</p><ul><li>No infrastructure needs to be maintained.</li><li>Storage is cheap, compute is costly. Therefore it is better to materialize results than to run the same query multiple times.</li><li>Tables can be partitioned and clustered.</li><li>Basic query tips go a long way to reduce costs and improve speed.</li></ul><p>With these things in mind, BigQuery can serve as a highly scalable, available and efficient data warehouse solution. Especially in the digital marketing space, where Google also provides many other tools (Analytics, Advertising, etc.), I believe it is by far the best solution for making data available for analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ceb162edd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Orchestration with Kestra]]></title>
            <link>https://medium.com/@angelaniederberger/learning-in-public-orchestration-with-kestra-0ec485da063e?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ec485da063e</guid>
            <category><![CDATA[kestra]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 21:02:12 GMT</pubDate>
            <atom:updated>2025-02-04T21:02:12.441Z</atom:updated>
            <content:encoded><![CDATA[<h4>Week 2 of the Data Engineering Zoomcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s-d5T-k6ExG6Lwjn" /><figcaption>Photo by <a href="https://unsplash.com/@realaxer?utm_source=medium&amp;utm_medium=referral">T K</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I’m writing this story while following the 2025 live cohort of the <a href="https://datatalks.club/blog/data-engineering-zoomcamp.html"><strong>Data Engineering Zoomcamp</strong></a>. To enhance the learning and grow a professional network, <a href="https://medium.com/u/bd5b4c871c78?source=post_page---user_mention--e5282f6f9d1b--------------------------------">Alexey Grigorev</a> and his team encourage a <strong>Learning in Public Approach</strong>, which means sharing my learning with others. In the second week, we built ETL pipelines with <a href="https://kestra.io/">Kestra</a>.</p><h3>What is Kestra?</h3><p>Kestra is an open-source, free to use orchestration platform. It allows users to build ETL workflows, coordinate the execution of (for example) python scripts and schedule tasks or perform backfills. In the user interface, the workflows are visualized as flow charts and the progress of the different steps in a pipeline is shown in Gantt diagrams. In case there are errors, it is easy to find them, since they are marked in red. You can access the logs with one click to understand what went wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRR5Go_Zotip-pe0J8AkTg.png" /><figcaption>Kestra Gantt Chart of a successfully executed workflow — Image by the Author</figcaption></figure><p>Workflows can be set up in different ways in Kestra. We used YAML files which contained all the inputs, variables and tasks for each flow. I decided to work with a Docker container including Kestra, so I was able to interact with the Kestra UI in my browser.</p><h3>ETL Pipelines</h3><p>The task was to transfer several dozen zipped .csv files from Github into one BigQuery dataset. With the ETL pipelines that we built in Kestra, we put together a record of the <a href="https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page">New York City Taxi Data</a>. The pipelines consisted of the following steps:</p><p><a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_2/kestra/01_gcp_keyvaluestore.yaml"><strong>Flow 1</strong></a>:</p><ul><li>set up the keys and values to be used later on (such as the service account key, the dataset name, etc.)</li></ul><p><a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_2/kestra/02_gcp_setup.yaml"><strong>Flow 2</strong></a>:</p><ul><li>create the required resources in the cloud: a Google Cloud Storage bucket and a BigQuery dataset.</li></ul><p><a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_2/kestra/03_taxi_data.yaml"><strong>Flow 3</strong></a>:</p><ul><li>download and unzip the file from Github using a shell command</li><li>upload the file to the storage bucket</li><li>transfer the data into an external table in BigQuery</li><li>add a unique identifier for each row as well as the file name in a second table to avoid duplicate rows</li><li>merge this second table into the main table (containing all the data from all the files)</li><li>purge the file in the storage bucket</li></ul><p><a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_2/kestra/04_taxi_data_scheduled.yaml"><strong>Flow 4</strong></a>:</p><ul><li>same as Flow 3, but with triggers that enable us to do backfills and to keep adding data on a schedule.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*S8pxRuOD_D4QBYjSDs_chA.png" /><figcaption>Scheduling backfills is easy in Kestra — Image by the Author</figcaption></figure><p>Once the flows were set up with their respective triggers, it was very easy to schedule backfills in the UI and transfer all the data to the BigQuery dataset.</p><h3>Summary</h3><p>In this module, I got acquainted with a new low-code tool for building data pipelines — Kestra. Having built data loading and transformation steps in python for work, I was surprised by how quickly we were able to get this process up and running. In addition, working with relatively large files showed the power of combining Kestra with the Google Cloud, where even tables with several million rows can be accessed and queried quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ec485da063e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning in Public: Docker, GCP and Terraform]]></title>
            <link>https://medium.com/@angelaniederberger/learning-in-public-docker-gcp-and-terraform-e5282f6f9d1b?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5282f6f9d1b</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[datatalksclub]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 18:33:33 GMT</pubDate>
            <atom:updated>2025-01-23T18:33:33.887Z</atom:updated>
            <content:encoded><![CDATA[<h4>Week 1 of the Data Engineering Zoomcamp</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2WfuXyvCtmjfRgy" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I’m writing this story while following the 2025 live cohort of the <a href="https://datatalks.club/blog/data-engineering-zoomcamp.html"><strong>Data Engineering Zoomcamp</strong></a>. To enhance the learning and grow a professional network, <a href="https://medium.com/u/bd5b4c871c78">Alexey Grigorev</a> and his team encourage a <strong>Learning in Public Approach</strong>, which means sharing my learning with others. So here’s what we covered in the first week:</p><ul><li>Docker</li><li>Google Cloud Platform</li><li>Terraform</li></ul><h3>Docker</h3><p>In short, Docker allows you to separate an <strong>application</strong> (like for example a database) from your <strong>infrastructure</strong> (like your laptop). It does this by ‘packaging’ the application inside a container, which contains everything needed to run the application. This container can then be ‘shipped’ for example to a colleague’s laptop or to a Virtual Machine running in the cloud.</p><p>I have used Docker in the past, but a colleague had previously created the setup, so I never had to start from scratch. I could just interact with the existing containers. The contents of this course helped me to understand how Docker containers are set up from the very beginning.</p><h4>Container Setup</h4><p>The curriculum contains a walk-through to recreate a setup with three separate containers:</p><ol><li>Container with a <a href="https://www.postgresql.org/">Postgres Database</a></li><li>Container with <a href="https://www.pgadmin.org/">PGAdmin</a></li><li>Container with the <a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_1/dockerdemo/ingest_data.py">data loading script</a> (Python)</li></ol><figure><img alt="A diagram showing the three docker containers" src="https://cdn-images-1.medium.com/max/528/1*uq2oUJZPcJ6RsqFbpW-FOQ.png" /><figcaption>Image by the Author</figcaption></figure><p>These containers need to be part of a network to facilitate communication between them. This then allows us to load data into the database from the container with the data loading script and to query (and modify) this data using SQL from the pgAdmin container. <strong>The point is that each of these containers runs in a completely isolated way, and therefore could be anywhere.</strong></p><h4>Core bash commands</h4><ul><li>$ docker run -it [...] my_container — download and spin up a Docker container interactively as specified</li><li>$ docker ps [-a] — list the containers that are currently running (or all with the -a flag).</li><li>$ docker stop my_container — stop a running container (or simply use Ctrl + d)</li><li>$ docker start my_container — start a container that was previously downloaded and stopped</li></ul><h3>Google Cloud Platform and Terraform</h3><p>These Google Cloud resources are relevant for the course:</p><ul><li>Storage Buckets</li><li>BigQuery</li></ul><p>In the course we covered how to set these up (and also destroy) them from the command line using a <a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_1/terrademo/main.tf">terraform file</a>. Variables that are used repeatedly (such as the storage location) can be defined in a separate <a href="https://github.com/Alessine/data-engineering-zoomcamp/blob/main/module_1/terrademo/variables.tf">variables file</a>. Once all the required cloud resources (e.g. buckets, datasets, etc.) are defined in these files, <strong>they can be set up in the cloud from the command line</strong>.</p><p>For me, this was one of the most interesting parts of week 1, since I work almost daily in the cloud, but I had never thought of automating the process of setting up cloud resources. Terraform makes this quite easy, including also the removal of resources after the task is done.</p><h4>Core bash commands</h4><ul><li>$ terraform init — install the terraform instance</li><li>$ terraform plan — print out a list of all the resources and their attributes that will be set up from the existing terraform file</li><li>$ terraform apply — actually set up the resources listed in the file</li><li>$ terraform destroy — remove all the resources listed in the file</li></ul><h3>Summary</h3><p>In week 1 of the Data Engineering Zoomcamp we learned how to set up Docker containers in a network and used them for data loading and exploration. We also got an introduction to the Google Cloud Platform and covered a simple way to automate the management of cloud resources. I gained a better understanding of how the Docker containers that I work with are set up and my new knowledge of how to automatically set up resources in the cloud will help me work more efficiently and at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5282f6f9d1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Web-scraping with AWS Free Tier]]></title>
            <link>https://medium.com/@angelaniederberger/automated-web-scraping-with-aws-72b7f80c2927?source=rss-c643a2defe9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b7f80c2927</guid>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[code-refactor]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Angela Niederberger]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 05:17:02 GMT</pubDate>
            <atom:updated>2022-07-02T06:47:35.489Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to move your scraping job into the cloud.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*glF5T7SlFbHhmBYS" /><figcaption>Photo by <a href="https://unsplash.com/@dpascoa?utm_source=medium&amp;utm_medium=referral">Daniel Páscoa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Table of Contents</h4><ol><li><a href="#d74f">Introduction</a></li><li><a href="#c2cf">Developing the Script</a><br>Extracting Data from a Website<br>Code Refactor</li><li><a href="#9fa2">Running the Scraping Job in the Cloud</a><br>AWS Basics<br>Saving to the S3 Bucket<br>Setting up the EC2 Instance<br>Automating the Script on the Instance</li><li><a href="http://5c15/">Conclusion</a></li></ol><h3><strong>Introduction</strong></h3><p>Have you ever faced a situation where you wanted to collect data from an online source at regular intervals? For me, creating my own datasets is one of the most fun, even artistic aspects of working with data. In this blog post I’ll take you through the process of automating a scraping job on AWS, I’ll share all the useful resources that I collected on this topic and finally, I’ll show you what my brand new data set looks like!</p><p>To develop and test the scraping script locally, I used conda to create a virtual environment with Python 3.10 and a couple of open source packages in it. You can find a list with all the details in the <a href="https://github.com/Alessine/aws_webscraping_automation/blob/master/requirements.txt">requirements file</a>.</p><p>Here’s what my setup on AWS looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*igsfVknMwUwKwTPa_Dem6w.png" /><figcaption>AWS Web-scraping Set-up (Image by the Author)</figcaption></figure><p>In short, I used an EC2 Instance (i.e. a virtual machine) to run my scraping script daily. As a trigger I set up a cron job on the same instance. In the last part of the scraping script, it saves a new CSV file with the day’s data to an S3 Bucket. That’s all I needed to complete the task, but read on for a more detailed description of the different steps in this process.</p><h3><strong>Developing the Script</strong></h3><p>Usually when I develop a script for some task, I start with basic exploration in a Jupyter Notebook. Once I know exactly what I want to do, I refactor my code: I write some functions and then switch to PyCharm to put together a clean script that can be executed from the command line. In the following subsections I will elaborate on this process.</p><h4><strong>Extracting Data from a Website</strong></h4><p>I decided to scrape the <a href="https://www.srf.ch/news/das-neueste">website of the Swiss national TV and Radio broadcaster SRF</a> daily to put together a data set of German news headlines. The website is static, so I worked with BeautifulSoup. For dynamic websites you would need to use Selenium.</p><p>In Firefox, I can inspect a website’s HTML code using Ctrl+Shift+C. If you’re using a different OS or browser you can find the relevant shortcut <a href="https://blog.hubspot.com/website/how-to-inspect">here</a>. In the Inspect mode I can see that for each news article, there’s a ‘kicker’, a ‘title’ and a ‘lead’, as well as the publication time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*oNeoyAuorpuCtO8mjLnCyw.png" /><figcaption>Using the HTML Inspector on the SRF News website to understand what elements to scrape (Image by the Author)</figcaption></figure><p>I want to extract all of these for each article. The first step is to request the HTML script from the website and to parse it with BeautifulSoup:</p><pre>import requests<br>from bs4 import BeautifulSoup<br>import pandas as pd<br>from datetime import date</pre><pre>url = “https://www.srf.ch/news/das-neueste”<br>page = requests.get(url)<br>soup = BeautifulSoup(page.content, “html.parser”)</pre><p>As a next step, the code below creates a list for each of these elements from all the articles.</p><pre>teaser_lists = soup.find_all(“div”, class_=”js-teaser-data”)<br>kickers = soup.find_all(“span”, class_=”teaser__kicker-text”)<br>titles = soup.find_all(“span”, class_=”teaser__title”)<br>leads = soup.find_all(“p”, class_=”teaser__lead”)</pre><p>Then I can iterate through these lists and store the data in a dictionary, which can easily be turned into a pandas DataFrame.</p><pre>news_snippet_dict = {<br>    “time_published”: [],<br>    “kicker”: [],<br>    “title”: [],<br>    “lead”: []<br>}</pre><pre>for (teaser_list, kicker, title, lead) in zip(teaser_lists, kickers,<br>    titles, leads):<br>    news_snippet_dict[“time_published”].append(teaser_list.get( <br>    “data-date-published”))<br>    news_snippet_dict[“kicker”].append(kicker.get_text())<br>    news_snippet_dict[“title”].append(title.get_text())<br>    news_snippet_dict[“lead”].append(lead.get_text())</pre><pre>news_snippets_df = pd.DataFrame(news_snippet_dict)</pre><p>As a final step, I turn the variable time_published into a timestamp and select only the news articles that were published on this day.</p><pre>news_snippets_df[&quot;time_published&quot;] = pd.to_datetime( <br>    news_snippets_df[&quot;time_published&quot;])</pre><pre>news_snippets_df = news_snippets_df[news_snippets_df[ <br>    &quot;time_published&quot;].dt.date == date.today()]</pre><p>This is it for the scraping. The code creates a DataFrame with all the available data for the day. If you want more information on how to use BeautifulSoup, there’s an excellent <a href="https://realpython.com/beautiful-soup-web-scraper-python/">resource</a> over at <em>RealPython</em>.</p><h4>Code Refactor</h4><p>In order to automate the code above, it needs to be adapted for a production environment, which generally means writing functions and integrating them into one script that can be executed from the command line. Another common requirement is to document the process well, for example by including a description and comments in functions and by creating a requirements file that lists all the packages that are required to run the script.</p><p>Here’s the function that I compiled from the previous code snippets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cba348d3c334449ae71d155ef355e3af/href">https://medium.com/media/cba348d3c334449ae71d155ef355e3af/href</a></iframe><p>In addition to this, it is common to write a main function which brings all the different steps together (in this case scraping and saving the data). I also normally implement some basic logging, so that in case there is an error, I can see where it happened. Here’s what my main function looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff8d8b73f1da594350bd346c539e43eb/href">https://medium.com/media/ff8d8b73f1da594350bd346c539e43eb/href</a></iframe><p>To complete the script, I added the following boilerplate code to define when the main function should be executed (i.e. whenever this script is run as the main script) and what should be done in this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f76bb02910b9671ae06aac9d95d03692/href">https://medium.com/media/f76bb02910b9671ae06aac9d95d03692/href</a></iframe><p>The full script can be found <a href="https://github.com/Alessine/aws_webscraping_automation/blob/master/src/main_local.py">here</a>.</p><p>After putting all of this together, I can run this file from the command line. I usually use a GNOME Terminal, since I’m working with a Ubuntu OS. Therefore, the following commands are in Bash. If you’re working on a Windows system, you can either <a href="https://hackernoon.com/how-to-install-bash-on-windows-10-lqb73yj3">install Bash</a> or try looking up equivalent commands for PowerShell.</p><p>So in my terminal, I first need to activate the virtual environment where the required packages are installed and navigate into the project folder. Then I simply tell Python to run the script:</p><pre>conda activate &lt;environment_name&gt;<br>cd &lt;path_to_project_folder&gt;<br>python src/main_local.py</pre><p>By running this script from the terminal, I can scrape data from the SRF News website and save it to a local folder with just one command.</p><p>In addition to the script, at this point I also created a <a href="https://github.com/Alessine/aws_webscraping_automation/blob/master/requirements.txt">requirements file</a> in which I listed the packages I’m using. It looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/071a5a2410ee96744c278034373d8195/href">https://medium.com/media/071a5a2410ee96744c278034373d8195/href</a></iframe><p>The file makes it very easy to create a new virtual environment similar to the one I’m using. This concludes the first part of this tutorial.</p><h3>Running the Scraping Job in the Cloud</h3><p>With the code refactor all done, I can move on to the next step, which is to automate the running of this script somewhere other than my own computer. I decided to use AWS for the automation of my web-scraping task, since it is one of the biggest cloud service providers with a really wide range of options available. In addition, there’s a ‘Free Tier’ plan for the first year which covers everything I’ve tried out so far.</p><h4>AWS Basics</h4><p>It is best to complete a few basic steps on AWS before using any of the services, just to ensure the set-up is according to their best practices, also in terms of security. To complete these steps correctly, I followed this <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-walkthroughs-managing-access-example1.html">walk-through</a> provided by AWS. It is very detailed, so I’m not going to repeat everything here.</p><p>Just to give a rough overview, here’s what I had to do:</p><ul><li>Sign up for an AWS account; this gave me my root user credentials. The credentials are best stored in the .aws folder in your /home.</li><li>With this root user, create an IAM user; give this user admin access. To avoid confusion resulting from the different user credentials, it is best to use a config file in your .aws folder.</li><li>Create the S3 bucket with the IAM user and attach a permissions policy to this bucket, which gives the IAM user read and write access.</li></ul><p>This is also a good time to set up <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html">billing alerts</a> to make sure the services do not exceed a certain budget.</p><h4>Saving to the S3 Bucket</h4><p>Now I can test this set-up by trying to write my data file from my computer to the S3 bucket. If the permissions are all in place, changing the folder path in my boilerplate (just below if __name__ == &#39;__main__&#39;:) to &quot;s3://srf-news-snippets/data&quot; should write the scraped data to the folder /data in the bucket named srf_news_snippets instead of a local folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04b6a59195bdbbdf26aa8e6b31f1a9d9/href">https://medium.com/media/04b6a59195bdbbdf26aa8e6b31f1a9d9/href</a></iframe><p>I hope this convinces you that writing data files to an AWS S3 Bucket is just as easy as writing them to a local folder. All we need is the pandas .to_csv() method. The full script for scraping and writing to the bucket can be found <a href="https://github.com/Alessine/aws_webscraping_automation/blob/master/src/main.py">here</a>.</p><h4>Setting up the EC2 Instance</h4><p>In the previous step, I showed how I used an S3 bucket to store data files in the cloud. Doing this becomes a lot more useful when the script is also run in the cloud, so the entire process is detached from my own machine. One way to achieve this is to set up a virtual machine in the cloud. The AWS Free Tier offers this with EC2 Instances. I’ve broken down the process into the following three steps:</p><p><strong>Give your User EC2 Access</strong></p><p>Give the admin user that you created before access to EC2 instances by adding the policy AmazonEC2FullAccess in the user’s profile (more information <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html">here</a>).</p><p><strong>Launch the Instance</strong></p><p>To do this, go to Services -&gt; EC2, scroll down a bit and click ‘Launch instance’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*BTfW2TGPH1s1p4lits5PkQ.png" /><figcaption>Launching an EC2 instance from the AWS Console (Image by the Author)</figcaption></figure><p>On the next screen, give your instance a name and choose your preferred options. I worked with an Ubuntu instance, 64-bit, of the type ‘t2.micro’, which is free tier eligible. Create a new key pair (default settings are fine here), so that you will be able to connect to the instance later on. Save this key file in your project folder. Then scroll down and click the button ‘Launch instance’.</p><p><strong>Give your Instance S3 Access</strong></p><p>You will want to use this instance to write to your S3 bucket, so the instance will require the permissions to do so. Standard AWS instructions to complete this process can be found <a href="https://aws.amazon.com/premiumsupport/knowledge-center/ec2-instance-access-s3-bucket/">here</a>. I tried to simplify it a bit below.</p><p>First, you need to create an IAM instance profile. Go to Services -&gt; IAM, in the Menu on the left click ‘Roles’ and then ‘Create role’. Select ‘AWS service’ and then ‘EC2’; click ‘Next’.</p><p>In the search bar, type “AmazonS3” and hit Enter. This shows you all the available options. I used the AmazonS3FullAccess policy to make sure the instance gets all the required permissions. Select it and click ‘Next’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieu8Q7WKsgKWbK5Mn70FFA.png" /><figcaption>Displaying all the permission policies related to “AmazonS3” on the AWS Console (Image by the Author)</figcaption></figure><p>Give this role a meaningful name and click ‘Create role’. Now you can assign this role to any of your instances, as needed.</p><p>As a second step, attach this newly created role to your instance. Go to Services -&gt; EC2, click ‘Instances’ and select your instance. Click on the ‘Actions’ drop down, select ‘Security’ and ‘Modify IAM role’. In the drop down on the next screen, you can select the role you just created. Finally, click ‘Update IAM Role’ to give your instance access to all your S3 buckets. This concludes the set-up and you can now start working with your instance!</p><h4>Automating the Script on the Instance</h4><p>For this next section I am again switching to my GNOME Terminal. These commands are in Bash, so if you’re working on a Windows System, you may need to find an alternative that works on your OS.</p><p><strong>Connect to your Instance</strong></p><p>Open up two different terminal windows. Use one of them to run commands on your local machine and the other to connect to your instance. In the first window:</p><ul><li>Give yourself full permission to access all files in the project directory:</li></ul><pre>chmod 700 &lt;path_to_project_folder&gt;</pre><ul><li>Navigate to your project folder with all your files:</li></ul><pre>cd &lt;path_to_project_folder&gt; </pre><ul><li>Restrict access to the EC2 key file (which should be stored here from before):</li></ul><pre>chmod 400 &lt;keyfile.pem&gt;</pre><ul><li>Then connect to the instance using your keyfile and the Public IPv4 DNS (you can find it in the AWS console by clicking on the Instance ID):</li></ul><pre>ssh -i “&lt;keyfile.pem&gt;” ubuntu@&lt;Public IPv4 DNS&gt;</pre><p>Here’s what my first terminal now looks like, just to give an idea of what you would expect to see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*5WfvtlKN2RpqA-64oDZHFg.png" /><figcaption>Terminal window connected to my EC2 instance (Image by the Author)</figcaption></figure><p>As you can see in the last line, I now have access to my instance via this terminal, so I can run commands in the cloud. If this did not work for you, check out these <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html">AWS guidelines</a>.</p><p><strong>Copy Files and install the Required Packages</strong></p><p>Now that I have access to my instance, I want to copy some files and install some packages on this instance, which will ultimately enable me to run my python scraping script on the instance.</p><p>In your second terminal window, navigate to the project folder:</p><pre>cd &lt;path_to_project_folder&gt;</pre><p>Copy the required files (requirements.txt &amp; main.py), again using the key file and the instance’s Public IPv4 DNS:</p><pre>scp -i &lt;keyfile.pem&gt; requirements.txt <a href="/service/mailto:ubuntu@ec2-18-157-79-164.eu-central-1.compute.amazonaws.com">ubuntu@</a>&lt;Public IPv4 DNS&gt;:~/<br>scp -i &lt;keyfile.pem&gt; src/main.py <a href="/service/mailto:ubuntu@ec2-18-157-79-164.eu-central-1.compute.amazonaws.com">ubuntu@</a>&lt;Public IPv4 DNS&gt;:~/</pre><p>Now switch back to your first terminal window, where you are still connected to your instance. You can check if the files are available there (use ls), navigate through folders (cd &lt;folder_name&gt;), create folders (mkdir &lt;folder_name&gt;) and move files (mv &lt;file_name&gt;).</p><p>You now need to install all your packages from the requirements file, but you will require pip to do this. So first, follow these <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-linux.html">instructions from AWS</a> to install pip on your instance (you can skip the first part about installing python). Once you have pip available, you can install your packages with the following command:</p><pre>pip install -r requirements.txt</pre><p>Once you have your files and packages ready on your instance, you can move on to the final step.</p><p><strong>Automate the Running of your Scraping Script</strong></p><p>Now you can finally run your script on the instance:</p><pre>python3 main.py</pre><p>This should save a data file to your S3 bucket, so even if you do not get any error message, go check if the file is available there.</p><p>To automate the running of the script, you can set up a simple cron job on the instance. First of all, check what timezone your instance is running in:</p><pre>timedatectl</pre><p>In my case this did not match my own timezone, so I used the following commands to list the available time zones and then set the instance to be in the same zone as I am.</p><pre>timedatectl list-timezones<br>sudo timedatectl set-timezone Europe/Zurich</pre><p>Then I set up a trigger to run the script daily at 11:50pm. To do this, I opened the cron file: crontab -e. Then I wrote in it: 50 23 * * * python3 main.py to run the script main.py every day at 23:50h, and saved the changes in this file with Ctrl.+O, then exited the editor with Ctrl.+X. If you’re not sure how to translate a specific timing into the cron logic, use this handy <a href="https://crontab.guru/">resource</a>.</p><p>This concludes the second part of the automated scraping set-up. I hope this documentation of the process that I followed will help you along the way to automating your own tasks.</p><h3>Conclusion</h3><p>To sum up, in this article I first showed how to scrape a website and refactor this code into a clean script. I then ran this script locally and saved the resulting file to a folder on my machine, as well as an S3 bucket in the cloud. Finally, I automated the running of the script using a cron job on an EC2 instance.</p><p>This simple setup has enabled me to scrape data from a website daily at the same time, without even thinking about it. In case you’re wondering what my data looks like, here’s an example <a href="https://github.com/Alessine/aws_webscraping_automation/blob/master/data/raw/2022-06-01_srf_news_snippets.csv">data file</a>. After a few months, I will have a unique, sizeable and interesting German text data set, on which I can try out different NLP tasks such as Named Entity Recognition, Topic Clustering and Sentiment Analysis.</p><p>I hope you found this tutorial useful! All the materials used in this article are available on <a href="https://github.com/Alessine">my GitHub</a> in this <a href="https://github.com/Alessine/aws_webscraping_automation">repository</a>. I will be happy to respond to your questions and comments and feel free to reach out to me on <a href="https://www.linkedin.com/in/angela-niederberger/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b7f80c2927" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>