<?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 Dai Dao on Medium]]></title>
        <description><![CDATA[Stories by Dai Dao on Medium]]></description>
        <link>https://medium.com/@ddao?source=rss-7beb56b63d56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*o4MW5DadQn3XX89WxYIFlw.jpeg</url>
            <title>Stories by Dai Dao on Medium</title>
            <link>https://medium.com/@ddao?source=rss-7beb56b63d56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:20:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ddao/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[Streaming tweets clustering with Spark on GCP]]></title>
            <link>https://medium.com/@ddao/streaming-tweets-clustering-with-spark-on-gcp-1184a3abd77a?source=rss-7beb56b63d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/1184a3abd77a</guid>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Dai Dao]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 14:50:24 GMT</pubDate>
            <atom:updated>2019-08-16T14:50:24.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*FFZd50xDAff05G_UIQCA3g.png" /></figure><p>This is another one of my side Data Engineering projects. The goal is to build a Threat Intelligence feed based on Twitter. Tweets are collected at intervals about a particular threats or topics of interest. From there tweets are filtered and clustered into groups of similar tweets. The output only shows the closest tweets to cluster centroid in each cluster to the analyst.</p><h3>GCP Infrastructure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVtxY5RpqPsXYqk9uRxn1Q.png" /><figcaption>(<a href="https://medium.com/@ddao/what-i-learned-from-finishing-the-udacity-data-engineering-capstone-acb7699aa921">Source</a>)</figcaption></figure><p>This architecture follows the GCP tutorial on counting trending hashtags (<a href="https://medium.com/@ddao/what-i-learned-from-finishing-the-udacity-data-engineering-capstone-acb7699aa921">Source</a>)</p><ol><li>The Tweet Generator program generates thousands of simulated tweets and publishes them to the tweets Cloud Pub/Sub topic. REPLACE by actual Tweets API to gather real-time tweets.</li><li>The Cloud Pub/Sub topic propagates newly received tweets, and the Spark streaming app subscribes to that topic for pull deliveries.</li><li>The Spark streaming app pulls the latest tweets at regular intervals, for example, every 20 seconds. Then it extracts and cluster the tweets over a sliding window, for example, the past 60 seconds.</li><li>At the end of each sliding window, the Spark streaming app saves the latest clusters to Cloud Datastore for persistent storage.</li><li>A Threat Intel platform can pull the clusters from DataStore and display to the analyst at regular intervals</li></ol><h3>Spark DStream</h3><p>I used Scala as the language of choice and Maven as build tool. The tricky part about the project is to set up the Streaming Cluster pipeline.</p><p>Spark has an API for Streaming KMeans, which acts like KMeans but keeps a memory of its previous cluster centroids, and the model can be used to predict as well as train on new streaming data.</p><p>Another tricky part of the project was to figure out how to write unit tests for the DStream pipeline, which involved defining your own Clock implementation using the Spark interface.</p><p>Sliding window mechanism:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nCLhXRWZq0srJpEk7kYtA.png" /><figcaption>(<a href="https://medium.com/@ddao/what-i-learned-from-finishing-the-udacity-data-engineering-capstone-acb7699aa921">Source</a>)</figcaption></figure><p>The Spark App pipeline executes at every 20 second interval, and it processes and clusters the tweets over the last 60 second window.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c222d0aec9ce2694459d3a40bb40b9ff/href">https://medium.com/media/c222d0aec9ce2694459d3a40bb40b9ff/href</a></iframe><p>I use TF-IDF features to process the tweets into a format for the KMeans model. One thing to note here is that in a production setting, the TF-IDF model should be pre-trained on a large corpus, and in the pipeline it only needs to be loaded up and predict on new data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc96c5db3d1e95e627c0645757fe09ad/href">https://medium.com/media/cc96c5db3d1e95e627c0645757fe09ad/href</a></iframe><p>This part of the code updates the KMeans model on new data, predict on new data and return the tweets that are closest to its centroid. Also to note here, we can train the KMeans model on a large corpus, then load it up in the production setting to make prediction and updates.</p><h3>Final notes</h3><p>There are lots of nuances when working with Cloud infrastructure. Although I started with a pre-configured project, as soon as I started to make custom changes things start to break.</p><p>I learnt a lot working with the Scala API and using the Maven build tool, as well as the Spark DStream API and how to make it work together with GCP DataProc, DataStore and PubSub APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1184a3abd77a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learned from finishing the Udacity Data Engineering Capstone]]></title>
            <link>https://medium.com/@ddao/what-i-learned-from-finishing-the-udacity-data-engineering-capstone-acb7699aa921?source=rss-7beb56b63d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb7699aa921</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Dai Dao]]></dc:creator>
            <pubDate>Fri, 26 Jul 2019 01:11:04 GMT</pubDate>
            <atom:updated>2019-07-26T01:11:04.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ec1tb-2QpcoZr8-jrcE8wQ.png" /></figure><h3><strong>Intro</strong></h3><p>This is my first experience with real Data Engineering. My tasks were to start with a lot of raw data from different sources, seemingly unrelated to each other, and somehow come up with a use case and design a data pipeline that could support those use cases. Time to put my data creativity hat on. The data potential is HUGE in this age.</p><blockquote>Sources of data provided by Udacity:</blockquote><blockquote>- US Immigration<br>- World Temperature<br>- US Demographics<br>- International Airport Codes</blockquote><p>The majority of Data Science works depends on what kind of data you have access to, and how to draw out the most relevant data attributes that can support your use cases and let the ML algorithms do its magic. I’ve read a lot of very creative use of data to do crazy inferences, like using Google house images and street views to infer potential car accidents at certain locations. Another crazy use case is combining traffic data, with car purchases, weather patterns, traffic lights patterns, to predict traffic. What I’m most interested in is Cybersecurity and Privacy use cases, which I will talk about in my next project. Note that all these data are in different forms and come from different sources. It would require a lot of Data Engineering work to extract, transform and load these into a usable data warehouses for analytics to happen.</p><p>The data sources provided by Udacity are not that interesting to me per se, but makes very good practice and preparation for my next project. Using the Snowflake schema, I’ve designed 8 normalized tables, such as airports, immigrants, state code, weather, etc … Using these normalized tables to design 2 analytics tables that are useful to consume, either for analytics or decision making, such as airport weather, and immigration demographics. During the process I had to deal with missing data, duplicates, malformed data, and so on.</p><p>Now that we got the data modelling out of the way, we’ll move on to my favourite topic, technologies. Particularly AWS, Spark and Airflow</p><h3><strong>AWS Infrastructure</strong></h3><p>First off, I’m particularly impressed at AWS CloudFormation, it’s such an easy and convenient way to deploy infrastructure with minimal effort, without spending hours clicking around multiple services trying to link them together. The configuration syntax is very intuitive and easy to learn.</p><figure><img alt="AWS Infrastructure (Source)" src="https://cdn-images-1.medium.com/max/1024/1*YTQqavuJ8cuMk0PoeqTLHA.png" /><figcaption>AWS Infrastructure (<a href="https://aws.amazon.com/blogs/big-data/build-a-concurrent-data-orchestration-pipeline-using-amazon-emr-and-apache-livy/">Source</a>)</figcaption></figure><p>An EC2 instance is used to host Airflow server, and an RDS instance is used as Airflow database, to store metadata about DAG runs, task completion, etc … Airflow is used to orchestrate the creation / termination of the EMR cluster. The basic workflow is: At the start of the DAG, create the EMR cluster and wait for completion. Once completed, start submitting Spark jobs to the cluster using Apache Livy REST API. When all jobs are completed, terminate the cluster.</p><h3>ETL</h3><p>I divided the workflow into 3 separate DAGs, which communicates with each other through Airflow Variables and SensorOperator</p><ul><li>dag_cluster: start the EMR cluster, and wait for all data transformation is finished, then terminate the cluster</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjSkGFGbmLxQfv0Uy_0bnQ.png" /></figure><ul><li>dag_normalize: wait for EMR cluster to be ready, then use Apache Livy REST API to create interactive Spark session on the cluster, submit a Spark script to read data from S3, do transformation and write the output to S3</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQglac-OOl4l2Bi0lah8XA.png" /></figure><ul><li>dag_analytics: wait for EMR cluster to be ready, and that normalized tables are processed, then read normalized tables to create analytics tables, and write to S3. This DAG handles immigration data, and runs in monthly intervals. Data is partitioned for 12 months from jan-2016 to dec-2016.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjSkGFGbmLxQfv0Uy_0bnQ.png" /></figure><h3>Spark</h3><ul><li>create_spark_session script:</li></ul><pre>def create_spark_session(master_dns, kind=&#39;spark&#39;):<br>   # 8998 is the port on which the Livy server runs<br>   host = &#39;http://&#39; + master_dns + &#39;:8998&#39;<br>   data = {&#39;kind&#39;: kind, &quot;conf&quot; : {<br>     &quot;spark.jars.packages&quot; : &quot;saurfang:spark-sas7bdat:2.0.0-s_2.11&quot;,                    <br>     &quot;spark.driver.extraJavaOptions&quot; : <br>                        &quot;-Dlog4jspark.root.logger=WARN,console&quot;}} .           <br>   headers = {&#39;Content-Type&#39;: &#39;application/json&#39;}<br>   response = requests.post(host + &#39;/sessions&#39;,   <br>                            data=json.dumps(data), headers=headers)<br>   logging.info(response.json())<br>   return response.headers</pre><ul><li>submit_state script: (to submit pyspark script to the session)</li></ul><pre>def submit_statement(session_url, statement_path, args = &#39;&#39;):<br>   statements_url = session_url + &#39;/statements&#39;<br>   with open(statement_path, &#39;r&#39;) as f:<br>       code = f.read()<br>   code = args + code<br>   data = {&#39;code&#39;: code}<br>   response = requests.post(statements_url, data=json.dumps(data),<br>   headers={&#39;Content-Type&#39;: &#39;application/json&#39;})<br>   logging.info(response.json())<br>   return response</pre><ul><li>Example Spark script:</li></ul><pre>from pyspark.sql.types import *<br>from pyspark.sql.functions import udf, col<br>import pyspark.sql.functions as F<br>from pyspark.sql.types import *import math<br>from datetime import datetime, timedelta<br>import sys<br>Logger = spark._jvm.org.apache.log4j.Logger</pre><pre>mylogger = Logger.getLogger(__name__)</pre><pre>def to_datetime(x):<br>    try:<br>        start = datetime(1960, 1, 1)<br>        return start + timedelta(days=int(x))<br>    except:<br>        return None<br>udf_to_datetime_sas = udf(lambda x: to_datetime(x), DateType())</pre><pre><br>def to_datetimefrstr(x):<br>    try:<br>        return datetime.strptime(x, &#39;%m%d%Y&#39;)<br>    except:<br>        return None<br>udf_to_datetimefrstr = udf(lambda x: to_datetimefrstr(x),DateType())</pre><pre><br>immigrant = spark.read.format(&#39;com.github.saurfang.sas.spark&#39;)\<br>                 .load(&#39;s3://decapstone/raw/i94_immigration<br>                    _data/i94_{}_sub.sas7bdat&#39;.format(month_year))\<br>                 .selectExpr(&#39;cast(cicid as int) AS cicid&#39;,          <br>                     &#39;cast(i94res as int) AS from_country_code&#39;, <br>                     &#39;cast(i94bir as int) AS age&#39;, <br>                     &#39;cast(i94visa as int) AS visa_code&#39;, <br>                     &#39;visapost AS visa_post&#39;, &#39;occup AS occupation&#39;, <br>                     &#39;visatype AS visa_type&#39;, &#39;cast(biryear as int)      <br>                                AS birth_year&#39;, &#39;gender&#39;)\                     <br>                 .withColumn(&quot;i94_dt&quot;, F.lit(month_year))</pre><pre>#<br>immigrant.write.partitionBy(&quot;i94_dt&quot;).mode(&quot;append&quot;).parquet(&quot;s3://de-capstone/lake/immigrant/&quot;)</pre><p>Few things to note:</p><ul><li>We can pass args from Airflow to the Spark script, such as execution date to partition the data</li><li>We can read the Spark session logs into Airflow</li></ul><pre>lines = requests.get(session_url + &#39;/log&#39;, headers={&#39;Content-Type&#39;: &#39;application/json&#39;}).json()[&#39;log&#39;]</pre><h3>Final Note</h3><p>There are lots of nuances in configuring Airflow and AWS, which I’ve learnt the hard way through doing this project. It’s really good preparation for me to embark on my own data journey. Stay tuned for my next project.</p><p>Project repo: <a href="https://github.com/dai-dao/udacity-data-engineering-capstone">https://github.com/dai-dao/udacity-data-engineering-capstone</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb7699aa921" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>