<?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 Kang Zhi Yong on Medium]]></title>
        <description><![CDATA[Stories by Kang Zhi Yong on Medium]]></description>
        <link>https://medium.com/@kangzhiyong1999?source=rss-c73ee2584865------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OBjWxjWLLKOAHwrx9DnvqQ.jpeg</url>
            <title>Stories by Kang Zhi Yong on Medium</title>
            <link>https://medium.com/@kangzhiyong1999?source=rss-c73ee2584865------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:57:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kangzhiyong1999/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[Learning Stream Processing in Kafka‍]]></title>
            <link>https://medium.com/@kangzhiyong1999/learning-stream-processing-in-kafka-67439d878e40?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/67439d878e40</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 05:27:28 GMT</pubDate>
            <atom:updated>2024-03-18T05:27:28.493Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main"><em>Data Engineering Zoomcamp Module 6: Stream Processing.</em></a><em> Check it out if you’re interested.</em></p><p>This is the 2nd part of the notes on stream processing using Apache Kakfa. It will be covering the basic concept of Kafka as well as the important topic like schema registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*BCcTZ6FxDVzuJ2lV.png" /></figure><p>How group by works in Kafka with different partition?</p><p>I was wondering how Kafka actually dealing with the group by function if the data is partitioned and the answer given by the instructor was the hashing of ‘key’ by producer when publishing message to the topic. For instance, the message keys. that can be divided by a number 2 with a remainder of 1 will goes to the same partition and it make sure the all the data is ingested into the same partition, hence the consumer have no further worries that the data fall into another partitions. If the key is defined as ‘null’, the round robin strategy is implemented with ‘0’, ‘1’, ‘0’, ‘1’ to ensure the data is equally partitioned, with approximately same amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvbSlwMdDjJXQNXcya0New.png" /></figure><blockquote>What is Global KTable in Kafka ?</blockquote><p>Imaging that we want to join the data in different partitions in different nodes, reshuffling across nodes is usually done behind the scene to get the jobs done. Although it seem to be fine, the computation is really expensive when the data volume get larger. Hence, there is where the Glbal KTable fit in, which the complete Global Table is saved in each node, somehow like the broadcasting concept that we have learnt in earlier module. However, it is important to note that the Global KTable is generally a small chunk of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPOOdzv8lfpwMO5bkdagig.png" /></figure><blockquote>Joining in Kakfa Streams</blockquote><p>In Kafka, we are allowed to join table across different two different topic via the message key, but there was certain restriction when came over to kinds of joins that can be performed as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ronuA1YBRu-VW4-imR0inQ.png" /></figure><p>Taking an example of inner stream to stream join with 10 seconds window. We can clearly see that the message in views and clicks were joined if it shared the same key and was within the 10s window, just like the A, C, F and G observation. However, we can observe a lag in G2 as G1 is ingested first. Remember that we are dealing with stream processing, one after another. For D and E, the is no key pairs for them, hence no joining was done. In contrast, B do have a key pair for views and clicks but it passed the 10s window, hence no inner join is performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGFf4j3d_q5Uqod5f1KKxQ.png" /></figure><blockquote>Kstream windowning</blockquote><p>There are four major type of windowning method in Kakfa as follow:</p><ul><li>Tumbling: Fixed size non overlapping</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RD1YZbrjtWtIgtb9Tyergw.png" /></figure><ul><li>Hopping: Fixed size and overlapping</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*K_So9ADvASsn4dTHLrPmWQ.png" /></figure><ul><li>Sliding: Fixed size, overlapping windows that work on difference between record timestamps</li><li>Session: Dynamically-sized, non-overlapping, data driven windows. Useful when we want to know active users logging in certain device.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*HKJIBJIL1DiBndNduF8SnQ.png" /></figure><blockquote>Schema Registry in Kafka</blockquote><p>It is really important to have a schema registry to ensure that the producer and consumer are saying the same language which the datatype is consistent across both user, preventing them from crashing, more like a guideline for not causing issue.</p><p>So, the schema served as a contract that registered by the producer prior publishing the message to the topic and consumed by consumers. When the topic is first established, the producer can register a schema in schema registry, and afterward a new version of schema can be updated while the schemas registry will then check for compatibility issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnu9j7Cg2CqVkc-34F0BuA.png" /></figure><p>For the compatibility case, it can be classified into 3 major types, the forward, backward and mixed compatibility, serving different purpose for the user.</p><ul><li>The forward compatibility</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fAWdwmLGlzNJc3mZMvTdQ.png" /></figure><p>The change of schema from producers will not affect the consumer with pervious version. Addition of an optional field in the producer schema can be one of the example for this</p><ul><li>Backward compatibility</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzjpEJJu9u4ivJspvlaecA.png" /></figure><p>The change of schema in newer version consumer will not affect the subscription of the topic although the producers are still in previous option. Similar example of addition of optional field can be applied here as well.</p><ul><li>Mixed compatibility</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YAPBPI9bAy86fIHqlB84g.png" /></figure><p>Can be known as full compatibility which producers can produce message with any version of schema and same applied to the consumers.</p><blockquote>Avro for schema registry</blockquote><p>For schema registry, Avro, a data serialization system is widely used due to its compatibility with Kafka. It has several benefits as follow:</p><ul><li>Smaller fileze (vs JSON)</li><li>Schema evolution</li><li>Avro clients provide automatic validation against schema</li></ul><blockquote>End</blockquote><p>Here I stopped parts of the notes for this module. If you want know more, you can checkout the video <a href="https://www.youtube.com/watch?v=SXQtWyRpMKs&amp;list=PL3MmuxUbc_hJed7dXYoJw8DoCuVHhGEQb&amp;index=72">here</a>. Special thanks to <a href="https://www.linkedin.com/in/ankushkhanna2/overlay/about-this-profile/">Ankush Khanna</a> for the lecture and all the figures are shared by him during the module.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67439d878e40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Apache Kafka works internally along with its configuration ? ‍]]></title>
            <link>https://medium.com/@kangzhiyong1999/how-apache-kafka-works-internally-along-with-its-configuration-4ec21f77a549?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec21f77a549</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 05:29:24 GMT</pubDate>
            <atom:updated>2024-03-12T05:36:29.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Apache Kafka works internally along with its configuration ? <a href="https://medium.com/dev-genius/feel-bored-on-public-dataset-9cd4cb5a6b28?source=your_stories_page-------------------------------------">👨🏻‍💻</a></h3><p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main"><em>Data Engineering Zoomcamp Module 6: Stream Processing.</em></a><em> Check it out if you’re interested.</em></p><p>Before going into the associated configuration with Kafka, let’s us refresh some of the terminology used in Apache Kafka for stream processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GNr0ONIQfuxuCx-G.jpg" /></figure><blockquote>What is message and logs in the Apache Kafka Broker/Cluster?</blockquote><p>Message is the stream of event that composed of 3 key components, the <em>key, timestamp </em>and <em>value </em>that being pushed to the topic by producer and eventually consumed by the consumer. Logs are defined as the data segments present in your disk that stored message in order fashion. <em>Broker</em> is then known to be the individual machine that run Kakfa while <em>cluster </em>is classified as a group of <em>broker </em>that work together.</p><p>Imagine that you’re ordering the “Happy Meal” from McDonald’s at counter, you’re now the producer who place the order as <em>message </em>to the topic of “customer order” at counter, then the consumer who will be the chef that consume your order and prepare the food accordingly to serve to you. The message then contains <em>key </em>like order id, <em>value </em>like your chosen beverage and also <em>timestamp </em>which record the exact time that the order is placed. <a href="https://emojipedia.org/hamburger">🍔</a> The message is particularly stored in the “customer order” topic and ordered by the timestamp in the system, just like the <em>logs </em>we discussed earlier. And last but not least, the ordering process might not just happened on you but also the people nearby, somehow similar to the concept of <em>broker </em>and <em>cluster. </em>Hope this analogy will help you in remembering the concept of Kafka more effectively.</p><blockquote>Moving into next part: The configuration that can be done in Kafka</blockquote><blockquote>Replication in Kafka</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkWaxH3ybx-coiPQf_ff7g.png" /></figure><p>In general, the created topic is residing in one of the node in the Kakfa cluster that will be subscribed by the producer and consumer to channel the message. However, what if the node broke down due to memory issue when the volume get larger or other unintended issue?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MA6i7sCc9tFL1KuKJdhCA.png" /></figure><p>That’s how replication in Kafka play its role in making sure the subscription of the consumer to the topic is always guaranteed when the leader node goes off and the follower will take over and become the leader. In this case, the replication factor is two, meaning the topic is replicated into two nodes accordingly.</p><blockquote>The retention time in Kafka</blockquote><p>Retention in Kafka is known be the amount of time logs will stay before they get deleted. It’s rather important when the data volume become enormously large as it might crash the machine due to memory issue. Hence, always think wisely before setting up the retention time for the Kafka topic.</p><blockquote>Partitioning in Kafka - The backbone of scaling in Kafka</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5wbIECx5ixOWlURli3MTw.png" /></figure><p>Let’s taking the 2 partitions as example as shown in the video by instructor, the message in the “Rides” topic is being partitioned into two, the RIDES-PAR0 and RIDES-PAR1 , which are then stored in different nodes in the cluster with a replication of 2. Just looking at how the topic is spread out in different nodes of the cluster, the consumers now might favor parallelism in fetching the message from the topic. This is the concept behind how the Kafka enable scaling. However, it’s extremely important to note that the consumers have to be in the same consumer group id to enable them to subscribe to the topic in parallel. If you’re only having 2 partitions but 3 consumers, the extra consumer will stay idle and smart enough to take over when one of the consumers die.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7qgv6XJWDG4y9byxeLJZQ.png" /></figure><blockquote>Offset in Kafka</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8a7bMkm1D4HDu8R9ORtUdQ.png" /></figure><p>For Apache Kafka, offset is described as the point where message has already been read by the consumer. Taking example as above, the consumer will inform the Kafka cluster or broker that they have commit message at the particular offset, store the information in another topic call __consumer-offset . If the consumer break down and goes off, the consumer in same consumer group id can take over, either using the strategies call latest or earliest . Inside the __consumer-offset , it store the consumer.group.id, topic, partition and offset as the message. This is particularly useful to check and start the new consumer based on these information using the auto.offset.reset option in Kafka. The latest option then ingest the data starting from the offset that have been stored in the __consumer-offset topic whilst the earliest ingest data that with the earliest record within the topic itself.</p><blockquote>Acks for producer configuration</blockquote><p>By definition, acks is defined as the number of brokers who need to be acknowledged for receiving the message before it is considered a successful write. 3 major option can be chosen</p><ul><li>0 =&gt; Does not wait for leader or replica broker to write the message to disk</li><li>1 =&gt; Waits for leader broker to write the message to disk</li><li>all =&gt; Waits for leader and all replica to write the message to disk</li></ul><blockquote>End</blockquote><p>Here I stopped parts of the notes for this module. If you want know more, you can checkout the video <a href="https://www.youtube.com/watch?v=SXQtWyRpMKs&amp;list=PL3MmuxUbc_hJed7dXYoJw8DoCuVHhGEQb&amp;index=72">here</a>. Special thanks to <a href="https://www.linkedin.com/in/ankushkhanna2/overlay/about-this-profile/">Ankush Khanna</a> for the lecture and all the figures are shared by him during the module.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec21f77a549" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restructure the Stream Processing With RisingWave ]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@kangzhiyong1999/restructure-the-stream-processing-with-risingwave-ef04fb440fce?source=rss-c73ee2584865------2"><img src="https://cdn-images-1.medium.com/max/2080/1*bRr650FtA_Yy2UfKp3aq4w.png" width="2080"></a></p><p class="medium-feed-snippet">If you&#x2019;re interested and wonder what are RisingWave, check out here.</p><p class="medium-feed-link"><a href="https://medium.com/@kangzhiyong1999/restructure-the-stream-processing-with-risingwave-ef04fb440fce?source=rss-c73ee2584865------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@kangzhiyong1999/restructure-the-stream-processing-with-risingwave-ef04fb440fce?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef04fb440fce</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 02:08:18 GMT</pubDate>
            <atom:updated>2024-03-09T02:11:05.616Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Feel Bored on Public Dataset? ‍]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.devgenius.io/feel-bored-on-public-dataset-9cd4cb5a6b28?source=rss-c73ee2584865------2"><img src="https://cdn-images-1.medium.com/max/2048/1*dlP6DupgP6h6gdKsWWAGgg.jpeg" width="2048"></a></p><p class="medium-feed-snippet">Why not having the data with your own interest by web scraping and faker module in python.</p><p class="medium-feed-link"><a href="https://blog.devgenius.io/feel-bored-on-public-dataset-9cd4cb5a6b28?source=rss-c73ee2584865------2">Continue reading on Dev Genius »</a></p></div>]]></description>
            <link>https://blog.devgenius.io/feel-bored-on-public-dataset-9cd4cb5a6b28?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd4cb5a6b28</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 15:20:30 GMT</pubDate>
            <atom:updated>2024-03-01T18:01:12.915Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Apache Spark in Google Cloud ]]></title>
            <link>https://blog.devgenius.io/apache-spark-in-google-cloud-58b3a5c09ad1?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/58b3a5c09ad1</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 08:30:25 GMT</pubDate>
            <atom:updated>2024-02-29T15:09:51.642Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main/05-batch"><em>Data Engineering Zoomcamp Module 5: Batch Processing</em></a><em>. Check it out if you’re interested.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*7RpksR0GnvEhRO6jBLMkrQ.png" /></figure><blockquote>First part: Connecting Apache Spark to Google Cloud Storage</blockquote><blockquote>Preparing the file: Copy file from Google Virtual Machine to S3</blockquote><p>Let’s say that you have the files in the disk of virtual machine, you can copy the data to google cloud storage via:</p><pre>gsutil cp -r path/in/virtual_machine gs://path/to/destination</pre><blockquote>Let’s download the connector for Hadoop to GCS</blockquote><ol><li>Download the Cloud Storage connector for Hadoop from the <a href="https://cloud.google.com/dataproc/docs/concepts/connectors/cloud-storage#clusters">Google Cloud documentation</a>. Remember to download the right version by first creating the lib/ in the virtual machine.</li><li>For my case, i download the latest connector version which compatile with my Apache Spark version of 3.3.4.2 via wget as follow</li></ol><pre>wget https://storage.googleapis.com/hadoop-lib/gcs/gcs-connector-hadoop3-latest.jar</pre><blockquote>Let’s connect to the GCS and read file</blockquote><ol><li>First of all, make sure you have your credential keys ready in the virtual machine and specify its path.</li></ol><pre>credentials_location = &#39;/path/to/your/credentials&#39;</pre><p>2. Setting up the configuration as</p><pre>conf = SparkConf() \<br>    .setMaster(&#39;local[*]&#39;) \<br>    .setAppName(&#39;test&#39;) \<br>    .set(&quot;spark.jars&quot;, &quot;./lib/gcs-connector-hadoop3-latest.jar&quot;) \<br>    .set(&quot;spark.hadoop.google.cloud.auth.service.account.enable&quot;, &quot;true&quot;) \<br>    .set(&quot;spark.hadoop.google.cloud.auth.service.account.json.keyfile&quot;, credentials_location)</pre><p>3. Before creating the SparkSession, we create a SparkConraxr for configuration purpose for haddop system</p><pre>sc = SparkContext(conf=conf)<br><br>hadoop_conf = sc._jsc.hadoopConfiguration()<br><br>hadoop_conf.set(&quot;fs.AbstractFileSystem.gs.impl&quot;,  &quot;com.google.cloud.hadoop.fs.gcs.GoogleHadoopFS&quot;)<br>hadoop_conf.set(&quot;fs.gs.impl&quot;, &quot;com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem&quot;)<br>hadoop_conf.set(&quot;fs.gs.auth.service.account.json.keyfile&quot;, credentials_location)<br>hadoop_conf.set(&quot;fs.gs.auth.service.account.enable&quot;, &quot;true&quot;)</pre><p>4. Create SparkSession as usual but specify its configuration</p><pre>spark = SparkSession.builder \<br>    .config(conf=sc.getConf()) \<br>    .getOrCreate()</pre><p>5. Read the file from GCS path and count the number of records</p><pre>df_green = spark.read.parquet(&#39;gs://module-5-batch-processing/pq/green/*/*&#39;)<br><br>df_green.count()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH0MaaN1yG_IA7CgoLflMw.png" /></figure><blockquote>Understand the Standalone Cluster before going to Google Cloud</blockquote><p>In Apache Spark, there are multiple cluster manager for resource management, namely the Spark Standalone, Yarn and Meso. Specifically for the Spark Standalone, it is the Spark’s own built-in resource manger, composed of master and the worker nodes which can be launched using the script by Apache Spark. Master node is responsible for the allocation of resources (CPU cores and memory) while worker nodes run the scheduled task by the master node and reported back to them.</p><p>For example, we can start the standalone master by executing from the spark directory</p><pre>./sbin/start-master.sh</pre><p>The running master node then can be accessed at the port:8080. As you can see, no worker yet assigned to the master node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWpw4mNt-Sq9XM2EwYYuKw.png" /></figure><p>We can then launch the workers as follow by specifying the master node url. There is only one worker with 4 cores and 16 memory as shown below. By default, the number if worker for each node is set to 1.</p><pre>./sbin/start-worker.sh spark://instance-20240222-020650.asia-southeast1-a.c.de-zoomcamp-412301.internal:7077</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6_i9iX4tnIqcavjsRQYwg.png" /></figure><p>As example, we then create a python script and submit the job to the master to be executed. The python script can be accessed <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY/blob/main/module_5_batch_processing/code/spark_sql.py">here</a>. After successfully running the job as the command below, the Application ID with status, duration submitted time can be accessed at the port:8080.</p><pre>URL=&quot;spark://instance-20240222-020650.asia-southeast1-a.c.de-zoomcamp-412301.internal:7077&quot;<br><br>spark-submit \<br>  --master &quot;${URL}&quot; \<br>  spark_sql.py \<br>    --input_green=data/pq/green/2021/*/\<br>    --input_yellow=data/pq/yellow/2021/*/\<br>    --output=data/report-2021</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMD0uTdi3NZw7Ux2sKuxAg.png" /></figure><p>Remember to stop the worker and master by:</p><blockquote>Important notes:</blockquote><ul><li>Running of this standalone cluster is difference when we running the SparkSession in the Jupyter Notebook. In Spark Standalone cluster, we explicitly separate the master and worker node. In contrast, Spark Session in Jupyter typically runs in “local” mode, where the Spark driver is instantiated within the Jupyter kernel process. In this mode, all Spark tasks are executed within the same process as the driver, without involving any external worker nodes or a separate cluster manager.</li><li>You may wonder what is driver here refer right? Driver is responsible for the convertion of the code written in R, Python, Scala or Jave into the logical execution plan. It communicate with the Spark’s Standalone cluster, YARN and Mesos for resources allocation for the application</li><li>Aside from that, we can choose the deployed mode as either “client” or “cluster” mode when we submitting the spark job.</li><li>In cluster mode, the driver runs one of the worker nodes, and shown as the driver in the Spark Web UI of the application. It is normally used to run production job</li><li>In client mode, the driver is run locally on the machine where the submission of Spark jobs are done. It is mainly for interative and debugging process. Remember that all the tasks are still run on the cluster worker nodes.</li></ul><blockquote>Submitting Spark Job in Dataproc</blockquote><ul><li>To submit the Spark Job in Dataproc, we first initiate the cluster by defining its region. It is best to choose the cluster region with your google cloud storage to ensure data transfer and compatability. Aside from that, we can choose one master node with 0 workers for testing before go to production</li><li>After launching the cluster, you can now submit the job by first selecting the job type to be pyspark and path to the python script.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6BZEYfszVzLLKvtAgrMWQ.png" /></figure><ul><li>since our python script also take in additional arguments like source file path and the output directory in google cloud storage, we need to specify it before running by inputing the 3 arguement in the Arguements section above</li></ul><pre>--input_green=gs://module-5-batch-processing/pq/green/2021/*/\<br>--input_yellow=gs://module-5-batch-processing/pq/yellow/2021/*/\<br>--output=gs://module-5-batch-processing/report-2021</pre><p>This conclude the way to submit the Spark job via Web UI. In the next part, we will show the way to submit Spark job through google SDK. Prior to that, make sure your service account have the permission to the Dataproc by enabling it in IAM &amp; Admin. To submit spark job as CLI, it can be done as command below:</p><pre># submit via cloud SDK<br>gcloud dataproc jobs submit pyspark \<br>  --cluster=cluster-zy \<br>  --region=us-central1 \<br>  gs://module-5-batch-processing/code/spark_sql.py \<br>  --  \<br>    --input_green=gs://module-5-batch-processing/pq/green/2021/*/\<br>    --input_yellow=gs://module-5-batch-processing/pq/yellow/2021/*/\<br>    --output=gs://module-5-batch-processing/report-2021</pre><blockquote>How to directly input the processed data from Spark jon directly to BigQuery?</blockquote><p>To directly save the processed data into BigQuery, we have to specify the temporary table in the python script. You may refer the complete script here.</p><pre>spark.conf.set(&#39;temporaryGcsBucket&#39;,&#39;dataproc-temp-us-central1-842668077187-4hd5ohjt&#39;)</pre><p>Besides, when we write the file, we have specify the as the bigquery destination as follow</p><pre>df_result.write.format(&#39;bigquery&#39;) \<br>    .option(&#39;table&#39;, output) \<br>    .save()</pre><p>We then can run the spark job in gcloud SDK as follow. Remember to define the .jar for spark to connect to BigQuery. The output is also the schema and table in BigQuery as trips_data_all.reports-2020</p><pre># submit and write directly to bigquery<br>gcloud dataproc jobs submit pyspark \<br>  --cluster=cluster-zy \<br>  --region=us-central1 \<br>  --jars=gs://spark-lib/bigquery/spark-bigquery-latest_2.12.jar \<br>  gs://module-5-batch-processing/code/spark_sql_to_bigquery.py \<br>  --  \<br>    --input_green=gs://module-5-batch-processing/pq/green/2021/*/\<br>    --input_yellow=gs://module-5-batch-processing/pq/yellow/2021/*/\<br>    --output=trips_data_all.reports-2020</pre><p>You can then check the result from BigQuery:</p><pre>SELECT * FROM `trips_data_all.reports-2020` LIMIT 10;</pre><p>It returns the records as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yUzffdtLcalZ_-n_j8sxQ.png" /></figure><blockquote>End</blockquote><p>Here, i stopped my notes on the last part of batch processing in Data Engineering Zoomcamp 2024, that given by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. If you’re interested, check out my <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY">Github repo</a> as well🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58b3a5c09ad1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/apache-spark-in-google-cloud-58b3a5c09ad1">Apache Spark in Google Cloud 🚀</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resilient Distributed Dataset in Spark]]></title>
            <link>https://medium.com/@kangzhiyong1999/resilient-distributed-dataset-in-spark-cfc7eba05a05?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfc7eba05a05</guid>
            <category><![CDATA[rdd]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 02:58:45 GMT</pubDate>
            <atom:updated>2024-02-26T02:58:45.536Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Resilient Distributed Dataset in Spark </strong>🚀</h3><p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main/05-batch"><em>Data Engineering Zoomcamp Module 5 Batch Processing</em></a><em>. Check it out if you’re interested.</em></p><p>Continued from the last article regarding the <a href="https://medium.com/@kangzhiyong1999/understand-the-spark-cluster-spark-dataframe-and-spark-sql-with-pyspark-efab224fd1e6">Spark DataFrame and Spark SQL</a>, we now explore the Resilient Distributed Dataset (RDD) which the Spark DataFrame are made available on top of it.</p><blockquote>Replicationg the Spark SQL query in RDD</blockquote><p>In this first part of the notes, we will discuss how the performance like filter and group by can be achieved in RDD. It’s not necessary to know about this, but its good to have an understanding on how the logic is implemented behind the scene if fine control is needed in the future as we now have a readily available Spark DataFrame and SQL API.</p><p>In comparison with the Spark DataFrame which have a pre-defined schema, the RDD can be understood as the collection of object which distributed across the machines (cores of computation power). For instance, the RDD is organized in row as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOdn1fAOGfBW8hxSVfazEw.png" /></figure><p>Taking the SQL Query as below:</p><pre>&quot;&quot;&quot;<br>SELECT<br>   <br>    date_trunc(&#39;hour&#39;, pickup_datetime) AS hour,<br>    PULocationID AS zone,<br>    <br>    SUM(total_amount) AS amount,<br>    COUNT(1) AS number_records<br>    <br>FROM<br>    green<br>WHERE<br>    pickup_datetime &gt;= &#39;2020-01-01 00:00:00&#39;<br>GROUP BY<br>    1,2<br><br>&quot;&quot;&quot;</pre><p>We will try to understand how this query can be implemented in term of RDD by first look into there WHERE clause. In RDD, we need to use the .filter() function to take in function to transform the data. In such case, we will be creating a customized function.</p><pre>from datetime import datetime<br><br>start_date = datetime(year=2020, month=1,day=1)<br><br>def filter_outliers(row):<br>    return row[&#39;lpep_pickup_datetime&#39;]&gt;=start_date</pre><pre>rdd.filter(filter_outliers).take(1)</pre><p>It then filter based on the condition we applied and return the output as rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*i1RO643azjImn1qCA-zhwQ.png" /></figure><p>The 2nd steps was the .map() function which will take in RDD and output as the RDD as well. For example, row as input and row as output. It’s useful to help us to transform data in rows. Hence, we use this .map() function to create a tuple of key and value as follow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvRVfLr69s1N43Mgira0mQ.png" /></figure><pre>def prepare_for_grouping(row):<br>    hour = row.lpep_pickup_datetime.replace(minute=0,second=0,microsecond=0)<br>    zone = row.PULocationID<br>    key = (hour, zone)<br>    <br>    amount = row.total_amount<br>    count = 1<br>    value = (amount, count)<br><br>    <br>    return (key, value)</pre><pre>example = rdd.filter(filter_outliers)\<br>    .map(prepare_for_grouping)\<br>    .take(5)<br>example</pre><p>It return the tuples format that we define:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBGk1Ke4jdMspts2KCLm3Q.png" /></figure><p>After creating the key and value for each row, we then use the reduceByKey() to group them accordingly to the key, which the reshuffling occur. Similar to map(), it take in RDD and output RDD as well but replication of key is eliminated by reducing them into one. The function will automatically sort the similar key together. Hence, the reduce action will be focusing on the value aggregation of two rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29dbY79213dvHvgR1363gA.png" /></figure><pre>def reduce(left_value,right_value): # calculate revenue<br>    left_amount, left_count = left_value<br>    right_amount, right_count = right_value<br>    <br>    output_amount = left_amount + right_amount<br>    output_count = left_count + right_count<br>    <br>    return (output_amount, output_count)</pre><pre>rdd.filter(filter_outliers)\<br>    .map(prepare_for_grouping)\<br>    .reduceByKey(reduce)\<br>    .take(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vpMdDFWBW9bl4WSFeKwGpg.png" /></figure><p>Using the function, we then can achieve the group by function then expressed in the SQL query. However, further transformaion can be done to unwrap the tuple with proper column name and schema as follow:</p><pre>from collections import namedtuple<br><br># give name to column <br>RevenueRow = namedtuple(&#39;RevenueRow&#39;,[&#39;hour&#39;,&#39;zone&#39;,&#39;revenue&#39;,&#39;count&#39;])<br><br># unwrap<br>def unwrap(row):<br>    return RevenueRow(<br>        hour= row[0][0],<br>        zone = row[0][1],<br>        revenue = row[1][0],<br>        count = row[1][1]<br>    )<br><br># define schema<br>from pyspark.sql import types<br><br>result_schema = types.StructType([<br>    types.StructField(&#39;hour&#39;, types.TimestampType(), True),<br>    types.StructField(&#39;zone&#39;, types.IntegerType(), True),<br>    types.StructField(&#39;revenue&#39;, types.DoubleType(), True),<br>    types.StructField(&#39;count&#39;, types.IntegerType(), True)<br>])<br><br># run the query in RDD<br><br>df_result = rdd.filter(filter_outliers)\<br>    .map(prepare_for_grouping)\<br>    .reduceByKey(reduce)\<br>    .map(unwrap)\<br>    .toDF(result_schema)</pre><p>As result, it return everything exact the same as the SQL query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKmKGZAkWF265y4Puzj9RA.png" /></figure><blockquote>The mapPartitions function in RDD</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KK3bPHHfYRNSNftaSuEwZg.png" /></figure><p>In contrast to map() function that take in rows, the mapPartition() take in the whole partition and output as partition as well. Extremely useful when we have big dataset, slicing them into chunks especially in machine learning.</p><p>Let’s say we have a well-trained machine learning model, we can then chunk the large dataset into smaller piece to input to the model and make prediction. For example, we have columns named ‘VendorID’, ‘lpep_pickup_datetime’, ‘PULocationID’ and ‘DOLocationID’ to predict ‘trip_distance’. The model look something like this (not like this in real life)</p><pre><br>def model_predict(df):<br>#     y_pred = model.predict(df)<br>    y_pred = df.trip_distance * 5<br>    return y_pred</pre><p>We can use the mapPartitions function to apply model at whole chunk as below by first making the chunk of RDD into the pandas DataFrame, then do prediction using the model.</p><pre>def apply_model_in_batch(rows):<br>    df = pd.DataFrame(rows, columns=columns)<br>    predictions = model_predict(df)<br>    df[&#39;predicted_duration&#39;] = predictions<br><br>    for row in df.itertuples():<br>        yield row</pre><p>The final result upon commnad below:</p><pre>df_predicts = duration_rdd\<br>        .mapPartitions(apply_model_in_batch)\<br>        .toDF()\<br>        .drop(&#39;Index&#39;)<br><br>df_predicts.select(&#39;predicted_duration&#39;).show()</pre><p>It returns the prediction as follow. Although it might not be the real-case used in business, but it show how mapPartition can be extremely useful in certain way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXzituGoEH5SEEATTCcN0A.png" /></figure><blockquote>End</blockquote><p>Here, i stopped my notes on the third parts of batch processing in Data Engineering Zoomcamp 2024, that given by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. The figure explaining Spark is also by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. If you’re interested, check out my <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY">Github repo</a> as well🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfc7eba05a05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand the Spark Cluster: Spark DataFrame and Spark SQL with PySpark ]]></title>
            <link>https://medium.com/@kangzhiyong1999/understand-the-spark-cluster-spark-dataframe-and-spark-sql-with-pyspark-efab224fd1e6?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/efab224fd1e6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark-dataframes]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 16:31:55 GMT</pubDate>
            <atom:updated>2024-02-23T16:34:06.283Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main/05-batch"><em>Data Engineering Zoomcamp Module 5 Batch Processing</em></a><em>. Check it out if you’re interested.</em></p><p>Continued from the last article regarding the <a href="https://medium.com/@kangzhiyong1999/how-to-run-spark-on-ubuntu-machine-in-google-cloud-pyspark-basic-24e277083d5a">installation of Spark on Ubuntu machine in Google Cloud</a>, we now explore the Spark DataFrame and Spark SQL in details using PySpark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*OhC-Mh7gLlGa7yu7K45ZPQ.png" /></figure><blockquote>Spark DataFrame</blockquote><p>We started the learning by first created the DataFrame from the parquet file that have been saved in last lesson.</p><pre># import library<br>import pyspark<br>from pyspark.sql import SparkSession<br><br># Create Spark Session<br>spark = SparkSession.builder\<br>    .master(&quot;local[*]&quot;)\<br>    .appName(&quot;test&quot;)\<br>    .getOrCreate()</pre><p>In Spark DataFrame, there is multiple function similar to Pandas DataFrame. However, Spark DataFrame has the concept of actions and transformation which the previous executed directly, known to be “EAGER” while latter known to be ‘LAZY’ which is not executed right away after calling the function. For example:</p><p>Transformation includes:</p><ul><li>.select(): Selecting columns</li><li>.filter(): Filtering columns</li><li>.join() : Joining table</li><li>.groupBy()</li></ul><p>While Actions includes:</p><ul><li>.show()</li><li>.head()</li><li>.take()</li><li>.write()</li></ul><p>If you’re checking the Spark UI, no jobs will be run if transformation is applied while jobs will be scheduled to run if actions is applied. Taking an example of code with the .show() actions in line as follow, the Spark UI will show the result for the transformation of .select() and .filter() .</p><pre>df.select(&quot;pickup_datetime&quot;,&quot;dropoff_datetime&quot;)<br>  .filter(df.hvfhs_license_num == &quot;HV0003&quot;).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKXUPnYvVRMnuGzJnV7AOA.png" /></figure><p>In the notebook, you will be receiving the results as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GiA6cDyEhHNf30uG_KSADQ.png" /></figure><p>Asides from that, the Spark have built-in function which can be applied on Spark DataFrame for data transformation. Taking the built-in function called `to_date()`, we demonstrated how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqNwTkc45vkQ2Ctnhkqwpw.png" /></figure><p>As shown in the code block, we first import the functions from pyspark.sql module as F . The subsequent code then show the creation of two additional column named pickup_date and dropoff_date by extract the date only from the pickup_datetime and dropoff_datetime column using the F.to_date function. We then select the columns that we need.</p><p>Apart from the pre-built function, we can create our own function which normally called User-Defined Function (UDF) in PySpark. For example, we have a business logic which want to transform the dispatching base number for the Spark DataFrame based on certain criteria as follow:</p><pre>def business_logic(base_num):<br>    num = int(base_num[1:])<br>    if num % 7 == 0:<br>        return f&#39;s/{num:03x}&#39;<br>    elif num % 6 == 0 :<br>        return f&#39;a/{num:03x}&#39;<br>    else:<br>        return f&#39;e/{num:03x}&#39;</pre><p>We can create a custom UDF in pyspark via</p><pre>business_logic_udf = F.udf(business_logic, returnType=types.StringType())</pre><p>We then can apply this function to the query we want as</p><pre><br>df \<br>    .withColumn(&#39;pickup_date&#39;,F.to_date(df.pickup_datetime))\<br>    .withColumn(&#39;dropoff_date&#39;,F.to_date(df.dropoff_datetime))\<br>    .withColumn(&#39;base_id&#39;,business_logic_udf(df.dispatching_base_num))\<br>    .select(&#39;base_id&#39;,&#39;pickup_date&#39;,&#39;dropoff_date&#39;,&#39;PULocationID&#39;,&#39;DOLocationID&#39;)\<br>    .show()</pre><p>It now returns, all the columns with the transformation we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGGrdLSnhAnJHefDBdmJOQ.png" /></figure><p>Use of this UDF is extremely useful when the SQL query become complicated and too many logic required. It make your query messy and not readable. Hence, UDF is here to solve the problem.</p><blockquote>Spark SQL</blockquote><p>With the green and yellow taxi data ready in the virtual machine in the parquet format with proper schema, we now ready to explore the Spark SQL. If you wonder how to download and infer the right schema for the taxi data, checkout the video <a href="https://www.youtube.com/watch?v=CI3P4tAtru4&amp;list=PL3MmuxUbc_hJed7dXYoJw8DoCuVHhGEQb&amp;index=56">here</a>.</p><p>Prior to the execution of SQL in Spark, we prepare the dataset by combining both of the green and yellow taxi dataset with its common columns by first identifying the common columns. You may check the notebook <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY/blob/main/module_5_batch_processing/code/Spark_SQL.ipynb">here</a> in details. In general, the code block below allow us to get to know which column is in common for both dataset, can give us list as an ouput for the common columns</p><pre>common_columns = []<br><br>for column in df_green.columns:<br>    if column in df_yellow.columns:<br>        common_columns.append(column)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*8Dajn4W4jJg8Tkf_eKwhNg.png" /></figure><p>As we need to combined both dataset, hence we need to explicitly add in another column named service_type to distinguish between green and yellow taxi as follow using the .lit() function frompyspark.sql.functions modules.</p><pre>df_green_sel = df_green \<br>            .select(common_columns)\<br>            .withColumn(&quot;service_type&quot;,F.lit(&#39;Green&#39;))<br><br>df_yellow_sel = df_yellow\<br>            .select(common_columns)\<br>            .withColumn(&quot;service_type&quot;,F.lit(&#39;Yellow&#39;))</pre><p>We then can combine both of the table using code</p><pre>## Union all the data<br>df_trips_data = df_green_sel.unionAll(df_yellow_sel)</pre><p>To check the combined data, we can check the result with what we have learned from the Spark DataFrame. It returns the number of records for both green and yellow dataset. From the Spark UI, we then can visualise how the jobs are being executed.</p><pre>df_trips_data.groupBy(&quot;service_type&quot;).count().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kTWBFX63x6QCx7ZjDMEYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXC7Yjf_7S45CEIK_arfyg.png" /></figure><p>Now, we take a look how SQL query can be done in Spark. Prior any running of SQL, we need to create a temporary view for the SQL to recognize which table to query from:</p><pre>df_trips_data.createOrReplaceTempView(&quot;trips_data&quot;)</pre><p>To get the similar results of what we done just now to count the records of green and yellow taxi data. The SQL Query can be run as code block below and it return the exact result as previously shown:</p><pre>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><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOOBqn26-aSRouVgBpmr3A.png" /></figure><p>Another example of SQL query done in the course is calculation of revenue for the dataset:</p><pre>df_result = spark.sql(&quot;&quot;&quot;<br>SELECT <br>    -- Reveneue grouping <br>    PULocationID AS revenue_zone,<br>    date_trunc(&#39;month&#39;, pickup_datetime) AS revenue_month, <br>    service_type, <br><br>    -- Revenue calculation <br>    SUM(fare_amount) AS revenue_monthly_fare,<br>    SUM(extra) AS revenue_monthly_extra,<br>    SUM(mta_tax) AS revenue_monthly_mta_tax,<br>    SUM(tip_amount) AS revenue_monthly_tip_amount,<br>    SUM(tolls_amount) AS revenue_monthly_tolls_amount,<br>    SUM(improvement_surcharge) AS revenue_monthly_improvement_surcharge,<br>    SUM(total_amount) AS revenue_monthly_total_amount,<br>    SUM(congestion_surcharge) AS revenue_monthly_congestion_surcharge,<br><br>    -- Additional calculations<br>    AVG(passenger_count) AS avg_montly_passenger_count,<br>    AVG(trip_distance) AS avg_montly_trip_distance<br>FROM<br>    trips_data<br>GROUP BY<br>    revenue_zone, revenue_month, service_type<br>&quot;&quot;&quot;)</pre><p>The SQL Query results then can be write to the parquet file with specific number of partition as follow:</p><pre>df_result.coalesce(1).write.parquet(&#39;data/report/revenue/&#39;, mode=&#39;overwrite&#39;)</pre><p>Using spark, we get the both benefits of SQL and python for transforming the data. However, let’s talk about the Spark Cluster and how join and Group By work in Spark Cluster in details.</p><blockquote>Understand the Spark Cluster</blockquote><p>Instead of discussing about running Spark on the local machine , we discuss about the Spark Cluster which made up of one master node and multiple executer nodes that commonly offered by Cloud Provider. Taking the figure drawn by the instructor as example, we can have a command called spark-submit to submit our Spark Jobs which written in python (pyspark) to the master node. The Spark UI can be accessed similiarly from our local machine which at the port 4040.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYRJ8LWk97pZs9qsm7FclA.png" /></figure><p>Once the jobs are submitted, the master node will coordinate with the executor nodes to distribute the tasks. If one of the executor goes off, the master node get notified and assign the task to another executor.</p><p>As the role of executor nodes, they need to pull the partitioned data (parquet file) from storage like data lake (S3, Google Cloud Storage etc) which commonly adopted nowadays to run the jobs assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwBmMPXmo2sySYRhy8ZwfQ.png" /></figure><p>In comparison with Spark that load data from S3 to the memory in the executor node, the old technology like HADOOP and HDFS download the files from S3, then store in the executors’ disk with redundancy as shown as figure below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ku1MWVjo4XBlDzLwnXK22g.png" /></figure><p>However, due to the introduction of data lake that reside inside the same data centre with the Spark Cluster, the network latency issue has been resolved while running the transformation. Hence, HDFS and Hadoop is getting less popular due to this reason. Aside from that, the in-memory processing in Spark is also a lot faster than the disk-processing in Hadoop ecosystem.</p><p>Aside from that, the submission of spark job can also be scheduled through the workflow orchestration tools like Airflow.</p><blockquote>How Group By Work in Spark Cluster ?</blockquote><p>Taking the SQL query below as the example,</p><pre>df_green.createOrReplaceTempView(&#39;green&#39;)<br><br>df_green_revenue = spark.sql(&quot;&quot;&quot;<br>SELECT<br>   <br>    date_trunc(&#39;hour&#39;, pickup_datetime) AS hour,<br>    PULocationID AS zone,<br>    <br>    SUM(total_amount) AS amount,<br>    COUNT(1) AS number_records<br>    <br>FROM<br>    green<br>WHERE<br>    pickup_datetime &gt;= &#39;2020-01-01 00:00:00&#39;<br>GROUP BY<br>    1,2<br><br>&quot;&quot;&quot;)<br><br>df_green_revenue.write.parquet(&#39;data/report/revenue/green&#39;)</pre><p>the Spark UI illustrate three stages of result, probably refer to the scanning of parquet file and group by for the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptHyPQF-1XLYQrOhED7Njw.png" /></figure><p>So, how the Group By work in Spark ? Looking in to stage 36 (stage 1), here is the stage where the data are read, filtered by the executors and initial group by was performed in each partitions as follow, resulting in the intermediate results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aW1fxsuL1btG9NCXDTlUA.png" /></figure><p>Looking at the stage 37 (stage 2), the intermediate results are <strong>RESHUFFLED (Exchange in the DAG in Spark UI), </strong>as each records in partition are move across its partition according to its key (which is the hour and zone in our query) before eventually write into the parquet file. The algorithm for this reshuffling is called <strong>External Merge Sort</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_cfBsSIePJ-dQxKlLpvcw.png" /></figure><p>Adding in the order by , resulting in another stage which apply the reshuffling concept as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*nb7MJi4RjHzMEQR8d2wSmQ.png" /></figure><p>As shown in figure below, the total of byte read during the shuffling process recorded specifically for the ORDER BY task in can be accessed as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*2fseAuU_8hnrsxrnK3n3Pw.png" /></figure><p>Apply the similar query to the yellow taxi dataset the total byte of shuffling is much more than the green taxi dataset as the file size is bigger. Both of them have 4 partitioned file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*Sa56ulhhNg87XlWLbsFWcQ.png" /></figure><blockquote>How Join Work in Spark Cluster ?</blockquote><p>To understand how JOIN work in Spark Cluster, it can be illustrated through joining two tables with similar size. For example, by joining the green_taxi_revenue and yellow_taxi_revenue as code block below:</p><pre><br># rename the column to avoid conflict<br>df_green_revenue_temp = df_green_revenue\<br>            .withColumnRenamed(&#39;amount&#39;,&#39;green_amount&#39;)\<br>            .withColumnRenamed(&#39;number_records&#39;,&#39;green_number_records&#39;)<br><br>df_yellow_revenue_temp = df_yellow_revenue\<br>            .withColumnRenamed(&#39;amount&#39;,&#39;yellow_amount&#39;)\<br>            .withColumnRenamed(&#39;number_records&#39;,&#39;yellow_number_records&#39;)<br><br># join the table<br>df_join = df_green_revenue_temp.join(<br>    df_yellow_revenue_temp,<br>    on=[&#39;hour&#39;,&#39;zone&#39;],<br>    how=&#39;outer&#39;<br>)<br><br># write to parquet file<br>df_join.write.parquet(&#39;data/report/revenue/total&#39;)</pre><p>Looking into the details of the job</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*sxY27pZi-5f_z797Bs0Lew.png" /></figure><p>The job contain 3 stages which first two stages reading the parquet file, while 3rd stages illustrate how two tables are joined and written into disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_sf3DprA91STje4JFRwlA.png" /></figure><p>The JOIN transformation work by first creating the composite key (hour, zone) and its records. Example:K1,Y2 in each of its partitions. Subsequently, it reshuffle to group the records with same key into the same partition as shown by the blue arrows. The records with same key will then be joined as shown in the red box. Since we using the outer join the records with unique key will keep its records and put null after joining with another table as shown below. The algorithm for this reshuffling is called <strong>External Merge Sort</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*-l5_BaES9rqm2RlzJ2gtOQ.png" /></figure><p>How about joining one large and one small table, it use different technique in resolving this. Taking the code block and the jobs completed in Spark UI as example</p><pre># large table<br>df_join = spark.read.parquet(&#39;data/report/revenue/total/&#39;)<br><br># small table<br>df_zones = spark.read.parquet(&#39;zones/&#39;)<br><br># join table<br>df_result = df_join.join(df_zones, df_join.zone == df_zones.LocationID)<br><br># save file<br>df_result.drop(&#39;LocationID&#39;,&#39;zone&#39;).write.parquet(&#39;tmp/revenue-zone&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*KHjLgrRHqfYpi3k0i9EIZg.png" /></figure><p>We now can observe a term called broadcast exchange for the join operation. So, how it works?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1imiy_c-pEP8HgQb8Dl2g.png" /></figure><p>Due to the smaller chunk size of the zones, it is being broadcasted to every partition in the executor to perform the join and reshuffling.</p><blockquote>End</blockquote><p>Here, i stopped my notes on the second parts of batch processing in Data Engineering Zoomcamp 2024, that given by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. The figure explaining Spark is also by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. If you’re interested, check out my <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY">Github repo</a> as well🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efab224fd1e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run Spark on Ubuntu Machine in Google Cloud (PySpark: Basic) ]]></title>
            <link>https://medium.com/@kangzhiyong1999/how-to-run-spark-on-ubuntu-machine-in-google-cloud-pyspark-basic-24e277083d5a?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e277083d5a</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 09:31:12 GMT</pubDate>
            <atom:updated>2024-02-22T09:39:06.146Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main/05-batch"><em>Data Engineering Zoomcamp Module 5: Batch Processing</em></a><em>. Check it out if you’re interested.</em></p><blockquote>What is batch processing?</blockquote><ul><li>Processing of huge chunk data according to schedule, from hourly, daily, weekly, 3 times per hour or every 5 minutes depend on the need of organization.</li></ul><blockquote>What technologies are commonly used?</blockquote><ul><li>Python Scripts ( Can be run anywhere, Kurbunetes/AWS Batch)</li><li>SQL (dbt)</li><li>Spark</li><li>Flink</li></ul><blockquote>What is the pros and cons of batch processing?</blockquote><ul><li>It is easy to manage and retry if the job failed</li><li>Ease of scaling. Change to larger machine is computation power hits the bottleneck.</li><li>Delay in update as main disadvantages.</li></ul><blockquote>What is Apache Spark?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*6b3qRwwOVoA88kjN.png" /></figure><p>A data processing engine in cluster which pull data from data lake, perform data transformation and load into data warehouse for analytical purpose. It support multiple language, such as JAVA, Scala, Python and R. In most of the company, pyspark is much popular. Can be used for batch jobs and streaming.</p><blockquote>When to use Spark?</blockquote><p>If you able to use SQL to transform data directly from the data lake like S3 and Google Cloud Storage, you can use software or service like AWS Athena, HIVE or PRESTO to transform data and load it into another dedicated data lake. If it’s not able to do so in SQL, it is where Spark come in to solve the problem, for example machine learning problem which Spark has dedicated library supporting the ML training, as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ib7MwJoajLmWEWsgrGqV1Q.png" /></figure><blockquote>Installing spark in linux, taking Virtual Machine in Google Cloud as example</blockquote><ul><li>Assuming that you have already had anaconda installed in the virtual machine, you can first create a directory called spark , then download java which is the pre-requisite to run Spark from this <a href="https://jdk.java.net/archive/">url</a> using wget. Remember that only choose between OpenJDK 11 or Oracle JDK 11 as spark requires version 8 or 11 specifically.</li><li>After unpacking the file using command tar xzfv , we should define JAVA home and add it to PATH by running this two commands,</li></ul><pre>export JAVA_HOME=&quot;${HOME}/spark/jdk-11.0.2&quot;<br>export PATH=&quot;${JAVA_HOME}/bin:${PATH}&quot;</pre><ul><li>You might need to define it every time login to the virtual machine if the environment variable get clear out.</li><li>Check the installation via java --version</li><li>Download spark from <a href="https://spark.apache.org/downloads.html">https://spark.apache.org/downloads.html</a> and unzip it through tar xzfv</li><li>Add it to PATH as well like what we did for JAVA</li><li>Remember to check the compatability issue of the lastest Apache Spark with the python module. For example, avoiding the use of spark-3.3.2 with pandas 2.1.4 version.</li></ul><pre>export SPARK_HOME=&quot;${HOME}/spark/spark-3.4.2-bin-hadoop3&quot;<br>export PATH=&quot;${SPARK_HOME}/bin:${PATH}&quot;</pre><ul><li>To avoid keying the PATH everytime log in, we can add the environment variable into the .bashrc file. So, it get run everytime when we log in to the virtual machine.</li><li>Then, we have to add in PYTHONPATH. Remember to check the py4j-0.10.9-src.zip version</li></ul><pre>export PYTHONPATH=&quot;${SPARK_HOME}/python/:$PYTHONPATH&quot;<br>export PYTHONPATH=&quot;${SPARK_HOME}/python/lib/py4j-0.10.9.7-src.zip:$PYTHONPATH&quot;</pre><blockquote>Creating a SparkSession</blockquote><p>To start with pyspark, first import the SparkSession from pyspark.sql</p><pre>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder \<br>  .master(&quot;local[*]&quot;)\<br>  .appName(&#39;test&#39;)\<br>  .getOrCreate()</pre><p>By specifying the .master(&quot;local[*]&quot;) , we can define the number of cpu used for the spark job. In this case, we use all the available resources to tun the jobs.</p><p>To test out the pyspark module, we load the data from a .csv file and write into .parquet file as follow. The file can be downloaded using this <a href="https://github.com/DataTalksClub/nyc-tlc-data/releases/download/fhvhv/fhvhv_tripdata_2021-01.csv.gz">url</a>.</p><pre>ds = spark.read\<br>    .option(&quot;header&quot;,&quot;true&quot;)\<br>    .csv(&quot;taxi+_zone_lookup.csv&quot;)<br><br>ds.write.parquet(&#39;zones&#39;)</pre><p>By forwarding the port to 4040 in the vs-studio, we can access all the command running in spark as UI as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZamcnRjm0Q1JDbiux4rdQ.png" /></figure><blockquote>First look on Pyspark</blockquote><p>After reading the data directly using the spark session, we can check the schema of the data via ds.schema . In response, it return the datatype used as follow:</p><pre>StructType([<br>  StructField(&#39;hvfhs_license_num&#39;, StringType(), True), <br>  StructField(&#39;dispatching_base_num&#39;,   StringType(), True), <br>  StructField(&#39;pickup_datetime&#39;,   StringType(), True), <br>  StructField(&#39;dropoff_datetime&#39;, StringType(), True), <br>  StructField(&#39;PULocationID&#39;, StringType(), True), <br>  StructField(&#39;DOLocationID&#39;, StringType(), True), <br>  StructField(&#39;SR_Flag&#39;, StringType(), True)<br>])</pre><p>You may notice that all the datatype are in string which is not good to use for further transformation. There is a way in nferring the schema directlt, by explicitly declare inferschema = True . Taking a small part of the data as example via the code below:</p><pre># take 1000 example of the data <br>! head  -n 10001 fhvhv_tripdata_2021-01.csv &gt; head.csv<br><br># we can read it directly from spark using inferScehema <br>spark_df = spark.read.csv(&quot;head.csv&quot;, header=True, inferSchema=True)<br><br>spark_df.schema</pre><p>The schema returned will be:</p><pre>StructType([<br>  StructField(&#39;hvfhs_license_num&#39;, StringType(), True), <br>  StructField(&#39;dispatching_base_num&#39;, StringType(), True), <br>  StructField(&#39;pickup_datetime&#39;, TimestampType(), True), <br>  StructField(&#39;dropoff_datetime&#39;, TimestampType(), True), <br>  StructField(&#39;PULocationID&#39;, IntegerType(), True), <br>  StructField(&#39;DOLocationID&#39;, IntegerType(), True), <br>  StructField(&#39;SR_Flag&#39;, StringType(), True)<br>])</pre><p>It returned the data with correct datatype. Aside from that, we can also use pandas.DataFrame to create spark.DataFrame as follow:</p><pre># read in pandas dataframe<br>pandas_df = pd.read_csv(&#39;head.csv&#39;)<br><br># create spark dataframe from pandas dataframe <br>spark_df = spark.createDataFrame(pandas_df)<br><br># print the schema<br>spark_df.schema</pre><p>The schema returned will be</p><pre>StructType([<br>  StructField(&#39;hvfhs_license_num&#39;, StringType(), True), <br>  StructField(&#39;dispatching_base_num&#39;, StringType(), True), <br>  StructField(&#39;pickup_datetime&#39;, StringType(), True), <br>  StructField(&#39;dropoff_datetime&#39;, StringType(), True), <br>  StructField(&#39;PULocationID&#39;, LongType(), True), <br>  StructField(&#39;DOLocationID&#39;, LongType(), True), <br>  StructField(&#39;SR_Flag&#39;, DoubleType(), True)<br>])</pre><p>From the inferred schema shown here, LongType() might not the good datatype compared to IntegerType() and the previos took up 8 bytes while latter took up 4 bytes. We might need to enforce a custom schema.</p><blockquote>How to infer custom schema in spark dataframe?</blockquote><p>To provide the custom schema, we can explicity define the datatype used as follow:</p><pre>from pyspark.sql import types<br><br># define schema<br>schema = types.StructType([<br>  types.StructField(&#39;hvfhs_license_num&#39;, types.StringType(), True), <br>  types.StructField(&#39;dispatching_base_num&#39;, types.StringType(), True), <br>  types.StructField(&#39;pickup_datetime&#39;, types.TimestampType(), True), <br>  types.StructField(&#39;dropoff_datetime&#39;, types.TimestampType(), True), <br>  types.StructField(&#39;PULocationID&#39;, types.IntegerType(), True), <br>  types.StructField(&#39;DOLocationID&#39;, types.IntegerType(), True), <br>  types.StructField(&#39;SR_Flag&#39;, types.StringType(), True)<br>])<br><br>ds = spark.read\<br>    .option(&quot;header&quot;,&quot;true&quot;)\<br>    .schema(schema)\<br>    .csv(&quot;fhvhv_tripdata_2021-01.csv&quot;)<br><br>ds.head(5)</pre><p>It return data with correct schema as shown which dropoff_datetime now is in TIMESTAMP :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*W09MuOHN_8VqVI29L51j7g.png" /></figure><blockquote>Save the large file into parquet with multiple partition</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4QsypUWMKAUrWZ6w6GDdQ.png" /></figure><p>Partitioning the large file into several partitions instead of one is extremely useful, as the worker in the spark cluster can work together, saving file into different partitions that they pointed to. No workers node will stay idle and wasted the processing power. Imagine you have only one file to be pointed to by multiple workers, only one worker is able to write to the location while others stay idle to wait the worker to get the job done.</p><p>Repartition of the large dataset can be achieved via ds.repartition(24) which will divide the dataset into 24 parts to be processed and write to the system. The code stay lazy until it is executed (save).</p><p>While writing to the .parquet file, the 4 core machine will get 6 tasks as we have 24 partitions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhafQMrkTzy0lGLOlee2pA.png" /></figure><p>Partitioning is an expensive operation, which expected to take up several time while running the commands. Total of 24 tasks were run to partitioned the data into 24 files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4mkdspbTWUw4rcwNnXmtA.png" /></figure><p>Files in the directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*H4A0xfrjV3lWs_qFkIGJeA.png" /></figure><blockquote>End</blockquote><p>Here, i stopped my notes on the first parts of batch processing in Data Engineering Zoomcamp 2024, that given by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. The figure explaining Spark is also by <a href="https://www.linkedin.com/in/agrigorev/">Alexey Grigorev</a>. If you’re interested, check out my <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY">Github repo</a> as well🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e277083d5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Ingestion with Data Loads Tool (dlt): Be the Magician in Data Engineering ]]></title>
            <link>https://medium.com/@kangzhiyong1999/data-ingestion-with-data-loads-tool-dlt-be-the-magician-in-data-engineering-44801b3dee87?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/44801b3dee87</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 14:35:37 GMT</pubDate>
            <atom:updated>2024-02-06T14:35:37.673Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you’re interested and wonder what are data load tools (dlt) , check out dltHub </em><a href="https://dlthub.com/docs/intro"><em>here</em></a><em>.</em></p><blockquote>Notes on <a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/blob/main/cohorts/2024/workshops/dlt_resources/data_ingestion_workshop.md">Data Engineering Zoomcamp Workshop 1: dlt</a>. Check it out if you’re interested.</blockquote><blockquote>The main purpose of this workshop</blockquote><ul><li>To get hands on experience on extracting data from APIs or files</li><li>Normalising and loading data</li><li>Incremental loading</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DasrnHA_kzzgq4u2lABV0Q.png" /></figure><blockquote>Why developing dlt?</blockquote><ul><li>Developed by <a href="https://www.linkedin.com/in/data-team/">Adrian</a> 10 years back to ease the pipeline development of data engineering.</li><li>A library that automates the tedious part of data ingestion: The Loading, Schema Management, Data Type Detection, Scalability, Scable Extraction. Ready to serve as the best pipelining tools for data engineer.</li><li>Due to its simplicity, dlt offer a 5–10x faster building time of pipeline. automatic schema changes remove the bulk of maintenance efforts, and governing your pipeline with schema evolution alerts and data contracts. It makes you to develop pipeline like a senior data engineer.</li></ul><blockquote>What is schema and why it’s important?</blockquote><p><em>The schema specifies the expected format and structure of data within a document or data store, defining the allowed keys, their data types, and any constraints or relationships.</em></p><p>In many cases, data engineers are the magician who infer the schema, thus data science teams can apply it seamlessly in their ML model in the production. However, the data format sometime is not explicitly defined with a schema, spending a relative portion of time for data engineer in fixing it. For example, .json and .csv file might not contain any metadata that stored the schema of the data, making them weakly typed and requires the extra normalisation or cleaning effort from data engineers. In contrast, some data format such as .parquet , avro and table in database are well-structured that can directly be applied by data science team.</p><blockquote>More aspects to be optimised than you think as a data engineer, other than just creating pipeline</blockquote><ul><li>With an easy to built data pipeline library like dlt, data engineer now can focus more on data storage optimisation, ensuring data quality and integrity, implementing effective data governance practices and continuously refining data architecture to meet the needs of organisation.</li><li>Ultimately, a good data engineer might involved in the strategic management and enhancement of the entire data lifecycle.</li></ul><blockquote>So, what is data load tools (dlt)?</blockquote><p>As refer to the <a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/blob/main/cohorts/2024/workshops/dlt_resources/data_ingestion_workshop.md">Github doc</a> in the workshop, <em>dlt is a python library created for the purpose of assisting data engineers to build simpler, faster and more robust pipelines with minimal effort, loading the data from various and often messy data sources into well-structured, live datasets.</em></p><blockquote>How does it help data engineer in developing pipeline?</blockquote><ul><li>Automated maintenance — with schema inference and evolution and alerts, and with short declarative code, maintenance becomes simple.</li><li>Run it where Python runs — on Airflow, serverless functions, notebooks. No external APIs, backends or containers, scales on micro and large infra alike.</li><li>User-friendly — declarative interface that removes knowledge obstacles for beginners while empowering senior professionals.</li><li>Post-Loading Transformations — dlt provides several options for transformations after loading the data, including using dbt, the dlt SQL client, or Pandas.</li></ul><blockquote>How dlt help in data extraction? Why we talk about this?</blockquote><p>There are few concept of storing data behind an API and we get different response depends on how the infrastructure built behind. For example,</p><ul><li>The API might return a secure file path to the .json or .parquet file in a public bucket that you can access the data</li><li>The API could be a database like mongodb, sql or other application that generally return records as JSON, the most common interchange format</li><li>RESTful api for business application then return records of data</li></ul><p>However, there are few concerns that usually addressed by the data engineers while preventing a pipeline from breaking:</p><ul><li>Hardware limits: Memory (RAM) management as we don’t know how big the size of data that we are extracting.</li><li>Network limit: Network failure. We can’t fix it directly but we can retry the network job until it succeed. For example, dlt library offers a requests “replacement” that has built in retries. Check the doc <a href="https://dlthub.com/docs/reference/performance#using-the-built-in-requests-client">here</a></li><li>Source API limit: The number of request per second that can be performed defined by each sources.</li></ul><blockquote>Best practice in managing memory</blockquote><p>You might wonder why memory management is so important? To answer this, Adrian has given us strong points on why and how to fix it.</p><p>In regards to “why”, filling the memory is BAD in a system (serverless function or orchestrators) that delegate the workloads to clusters of small workers (now they have a small memory) as it does not just lead to the crash of pipeline but also entire containers that shared the memory with those workers. The same analogy might applied to disk but the disk might be sufficient in most of the case as we are using external drive that mapped to a storage bucket like GCS or S3.</p><p>To fix it, the best solution is to control the maximum memory that we can use as we do not know the volume of data upfront and unable to scale dynamically on hardware during runtime. In other word, we control the maximum use of memory by streaming the data. <em>Streaming </em>here refer to the processing of data by event or chunks rather than doing the bulk operations.</p><p>Some classic example fo streaming where data is transferred chunk by chunk to event by event:</p><ul><li>Between an audio broadcaster and an in-browser audio player</li><li>Between a server and a local video player</li><li>Between a smart home device or IoT device and your phone</li><li>between google maps and your navigation app</li><li>Between instagram live and your followers</li></ul><p>What do data engineers do? We usually stream the data between buffers, such as</p><ul><li>from API to local file</li><li>from webhooks to event queues</li><li>from event queue (Kafka, SQS) to Bucke</li></ul><blockquote>Streaming via generators in python</blockquote><p>To achieve the streaming concept, Adrian provided us a clear concept on how generators in python could help in memory management effectively. <em>Generators </em>here refer to a function that can return multiple times</p><p>For example, a regular function might collect data in memory as shown below. The data is collected row by row in a list called data which will eventually break when the volume of data exceed our memory:</p><pre>def search_twitter(query):<br> data = []<br> for row in paginated_get(query):<br>  data.append(row)<br> return data<br><br># Collect all the cat picture data<br>for row in search_twitter(&quot;cat pictures&quot;):<br>  # Once collected, <br>  # print row by row<br> print(row)</pre><p>In comparison, we can modify the function as follow, which we yield each row as we get the data without collecting it into memory. We only run this generator and handle the data item by item</p><pre>def search_twitter_modified(query):<br> for row in paginated_get(query):<br>  yield row<br><br># Get one row at a time<br>for row in search_twitter_modified(&quot;cat pictures&quot;):<br> # print the row<br> print(row)<br>  # do something with the row such as cleaning it and writing it to a buffer<br> # continue requesting and printing data  </pre><p>When calling the for row in search_twitter_modified(&quot;cat pictures&quot;) , the the print statement is executed as long as the first data items is yielded, thus we don’t need to wait so long to have entire dataset loaded into memory.</p><p>If we want to get all the values at once from generators instead of one by one, we need to first execute the generator and collect the data, data = list(search_twitter_modified(&quot;cat picture&quot;) which collect all the data into list in memory</p><blockquote>Taking NYC taxi dataset as example</blockquote><ol><li>Grabbing data through an API</li></ol><p>For this data extraction through API, Adrian has helped us to create an API that serve the NYC taxi dataset, which the API documentation is as follow:</p><ul><li>There are a limited number of records behind the API</li><li>The data can be requested page by page, each page containing 1000 records</li><li>If we request a page with no data, we will get a successful response with no data</li><li>so this means that when we get an empty page, we know there is no more data and we can stop requesting pages — this is a common way to paginate but not the only one — each api may be different.</li><li>Method (GET) at URL (https://us-central1-dlthub-analytics.cloudfunctions.net/data_engineering_zoomcamp_api)</li><li>Parameer: page(integer). Represents the page number you are requesting. Defaults to 1.</li></ul><p>In this work, we need to request page by page until there are no more data. At this point, we do not know any information about the size of the data behind the API. Hence, we need to use a generator to avoid having an undetermined amount of data into RAM.</p><p>Using this approach, we have the pros and cons as follow:</p><ul><li><strong>Pros</strong>: Easy memory management thanks to api returning events/pages</li><li><strong>Cons</strong>: Low throughput, due to the data transfer being constrained via an API.</li></ul><p>The code for the generator is as follow:</p><pre>import requests<br><br>BASE_API_URL = &quot;https://us-central1-dlthub-analytics.cloudfunctions.net/data_engineering_zoomcamp_api&quot;<br><br># I call this a paginated getter<br># as it&#39;s a function that gets data<br># and also paginates until there is no more data<br># by yielding pages, we &quot;microbatch&quot;, which speeds up downstream processing<br><br>def paginated_getter():<br>    page_number = 1<br><br>    while True:<br>        # Set the query parameters<br>        params = {&#39;page&#39;: page_number}<br><br>        # Make the GET request to the API<br>        response = requests.get(BASE_API_URL, params=params)<br>        response.raise_for_status()  # Raise an HTTPError for bad responses<br>        page_json = response.json()<br>        print(f&#39;got page number {page_number} with {len(page_json)} records&#39;)<br><br>        # if the page has no records, stop iterating<br>        if page_json:<br>            yield page_json<br>            page_number += 1<br>        else:<br>            # No more data, break the loop<br>            break<br><br>if __name__ == &#39;__main__&#39;:<br>    # Use the generator to iterate over pages<br>    for page_data in paginated_getter():<br>        # Process each page as needed<br>        print(page_data)</pre><p>In short, the page_number designate the records that being requested until no more records in the page. Example of output could be something like as figure below. It indicates that the data is yielded by items in the for loop rather than loaded into memory in one big chunk, crashing the machine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*TPJR9ueXVpu6VTZm3J9Hfw.png" /></figure><p>2. Grabbing data through simple download (same dataset). <strong>NOT an API !</strong></p><p>This second approach of downloading data is not from the API but a file that everyone can download from storage directly. Why organisation implement this strategy?</p><p>The answer for this are most likely to be the throughput and cost. A restful api that return data has to read data from storage and return to you based on certain logic, thus taking up time and money if the dataset is large, eventually creating a bottleneck.</p><p>Adrian has then shown us the comparison between two methods, through a generator or without. He first showed us the method which load entire dataset into memory, in turn it has a pro of high throughput but a con of using up memory to hold all the data which is <strong><em>NOT GREAT ! </em></strong>According to him, “<em>this is a less than ideal approach because if the file size is unknown, we run the risk of running out of memory. In the case of machines that run multiple jobs, an out of memory error runs the risk of killing not just the current jobs but also anything else running on the machine at the time — a situation most data engineers </em><strong><em>really really</em></strong><em> like to avoid.”</em></p><pre>import requests<br>import json<br><br>url = &quot;https://storage.googleapis.com/dtc_zoomcamp_api/yellow_tripdata_2009-06.jsonl&quot;<br><br>def download_and_read_jsonl(url):<br>    response = requests.get(url)<br>    response.raise_for_status()  # Raise an HTTPError for bad responses<br>    data = response.text.splitlines()<br>    parsed_data = [json.loads(line) for line in data]<br>    return parsed_data<br><br>downloaded_data = download_and_read_jsonl(url)<br><br>if downloaded_data:<br>    # Process or print the downloaded data as needed<br>    print(downloaded_data[:5])  # Print the first 5 entries as an example</pre><p>In contrast to that, stream download can be achieved if using a generator,. Using this approach it have the pros and cons as follow:</p><ul><li><strong>Pros</strong>: High throughput, easy memory management, because we are downloading a file</li><li><strong>Cons</strong>: Difficult to do for columnar file formats, as entire blocks need to be downloaded before they can be deserialised to rows. Sometimes, the code is complex too.</li></ul><pre>import requests<br>import json<br><br>def download_and_yield_rows(url):<br>    response = requests.get(url, stream=True)<br>    response.raise_for_status()  # Raise an HTTPError for bad responses<br><br>    for line in response.iter_lines():<br>        if line:<br>            yield json.loads(line)<br><br># Replace the URL with your actual URL<br>url = &quot;https://storage.googleapis.com/dtc_zoomcamp_api/yellow_tripdata_2009-06.jsonl&quot;<br><br># Use the generator to iterate over rows with minimal memory usage<br>for row in download_and_yield_rows(url):<br>    # Process each row as needed<br>    print(row)</pre><p>In a jsonl file that prepared by Adrian, each line is a json document, or a “row” of data, so he implement a code to yield them as they get downloaded. This allows us to download one row and process it before getting the next row.</p><p>Comparison between two approaches, using a generator for loading data take relatively less time (~0.07 seconds) as compared to the first approach which bulk of data is loaded first (~0.27 seconds)</p><ul><li>Without Generators</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Skp56jQcxCW_sEiUA3g56Q.png" /></figure><ul><li>Generators</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*MI2eEc6B1mIMvOfbNamrxg.png" /></figure><blockquote>Using dlt library to load data into DuckDB</blockquote><p>In the workshop, Adrian also showed us an easy way to test our code in a development environment by populating data into <a href="https://duckdb.org/"><strong>DuckDB</strong></a><strong>, </strong>an in-process SQL OLAP database management system prior the deployment to BigQuery and etc. It can easily achieved to test the data loading with generator approach via:</p><pre> import dlt<br><br># define the connection to load to.<br># We now use duckdb, but you can switch to Bigquery later<br>generators_pipeline = dlt.pipeline(destination=&#39;duckdb&#39;, dataset_name=&#39;generators&#39;)<br><br><br># we can load any generator to a table at the pipeline destnation as follows:<br>info = generators_pipeline.run(paginated_getter(),<br>          table_name=&quot;http_download&quot;,<br>          write_disposition=&quot;replace&quot;)<br><br># the outcome metadata is returned by the load and we can inspect it by printing it.<br>print(info)<br><br># we can load the next generator to the same or to a different table.<br>info = generators_pipeline.run(stream_download_jsonl(url),<br>          table_name=&quot;stream_download&quot;,<br>          write_disposition=&quot;replace&quot;)</pre><p>you can then check the data in database via SQL query after establishing a connection with DuckDB as follow, which i personally modified to count the number of column to check either both from API or file have same amount of rows:</p><pre>import duckdb<br><br>conn = duckdb.connect(f&quot;{generators_pipeline.pipeline_name}.duckdb&quot;)<br><br># let&#39;s see the tables<br>conn.sql(f&quot;SET search_path = &#39;{generators_pipeline.dataset_name}&#39;&quot;)<br>print(&#39;Loaded tables: &#39;)<br>display(conn.sql(&quot;show tables&quot;))<br><br># and the data<br><br>print(&quot;\n\n\n http_download table below:&quot;)<br><br>rides = conn.sql(&quot;SELECT count(*) FROM http_download&quot;).df()<br>display(rides)<br><br>print(&quot;\n\n\n stream_download table below:&quot;)<br><br>passengers = conn.sql(&quot;SELECT count(*) FROM stream_download&quot;).df()<br>display(passengers)</pre><blockquote>Normalising data using dlt</blockquote><p>Data cleaning by the data people can be divided into two kinds:</p><ul><li>Normalising data without changing its meaning</li><li>Filtering data for a use case which changes its meaning.</li></ul><p>Parts of the data cleaning work is just the metadata work according to Adrian which data engineer spend time on:</p><ul><li>Add types (string to number, string to timestamp, etc)</li><li>Rename columns: Ensure column names follow a supported standard downstream — such as no strange characters in the names.</li><li>Flatten nested dictionaries: Bring nested dictionary values into the top dictionary row.</li><li>Unnest lists or arrays into child tables: Arrays or lists cannot be flattened into their parent record, so if we want flat data we need to break them out into separate tables.</li></ul><p>A clear example is parsing .json into database which requires a lots of work to be done. Why we not using JSON?</p><ul><li>Lack of schema in json document</li><li>Types are not enforced between rows of json. 23 in a row can be denoted as twenty-three and 23.00 . Or in some systems, you might have a dictionary for a single record, but a list of dicts for multiple records. This could easily lead to applications downstream breaking.</li><li>We cannot just use json data easily, for example we would need to convert strings to time if we want to do a daily aggregation.</li><li>Reading json loads more data into memory, as the whole document is scanned. It is not cost-effective and time-efficient as compare to .parquet format.</li><li>JSON is not fast to aggregate and search.</li></ul><p>In the workshop, Adrian showed an example of how JSON is parsed into database easily using dlt library, successfully</p><ul><li>flatten dictionaries into the base row</li><li>flatten lists into a seperate table</li><li>convert time strings into time type</li></ul><p>Example of JSON file with nested dictionary and list</p><pre>data = [<br>    {<br>        &quot;vendor_name&quot;: &quot;VTS&quot;,<br>    &quot;record_hash&quot;: &quot;b00361a396177a9cb410ff61f20015ad&quot;,<br>        &quot;time&quot;: {<br>            &quot;pickup&quot;: &quot;2009-06-14 23:23:00&quot;,<br>            &quot;dropoff&quot;: &quot;2009-06-14 23:48:00&quot;<br>        },<br>        &quot;Trip_Distance&quot;: 17.52,<br>        # nested dictionaries could be flattened<br>        &quot;coordinates&quot;: {<br>            &quot;start&quot;: {<br>                &quot;lon&quot;: -73.787442,<br>                &quot;lat&quot;: 40.641525<br>            },<br>            &quot;end&quot;: {<br>                &quot;lon&quot;: -73.980072,<br>                &quot;lat&quot;: 40.742963<br>            }<br>        },<br>        &quot;Rate_Code&quot;: None,<br>        &quot;store_and_forward&quot;: None,<br>        &quot;Payment&quot;: {<br>            &quot;type&quot;: &quot;Credit&quot;,<br>            &quot;amt&quot;: 20.5,<br>            &quot;surcharge&quot;: 0,<br>            &quot;mta_tax&quot;: None,<br>            &quot;tip&quot;: 9,<br>            &quot;tolls&quot;: 4.15,<br>      &quot;status&quot;: &quot;booked&quot;<br>        },<br>        &quot;Passenger_Count&quot;: 2,<br>        # nested lists need to be expressed as separate tables<br>        &quot;passengers&quot;: [<br>            {&quot;name&quot;: &quot;John&quot;, &quot;rating&quot;: 4.9},<br>            {&quot;name&quot;: &quot;Jack&quot;, &quot;rating&quot;: 3.9}<br>        ],<br>        &quot;Stops&quot;: [<br>            {&quot;lon&quot;: -73.6, &quot;lat&quot;: 40.6},<br>            {&quot;lon&quot;: -73.5, &quot;lat&quot;: 40.5}<br>        ]<br>    },<br>    # ... more data<br>]</pre><p>By running a pipeline using dlt libary as follow:</p><pre># define the connection to load to. <br># We now use duckdb, but you can switch to Bigquery later<br>pipeline = dlt.pipeline(destination=&#39;duckdb&#39;, <br>      dataset_name=&#39;taxi_rides&#39;)<br><br># run the pipeline with default settings, and capture the outcome<br>info = pipeline.run(data, <br>                    table_name=&quot;rides&quot;, <br>                    write_disposition=&quot;merge&quot;,<br>                    primary_key=&quot;record_has&quot;                    <br>)<br><br># show the outcome<br>print(info)</pre><p>and inspection of database:</p><pre># show the outcome<br><br>conn = duckdb.connect(f&quot;{pipeline.pipeline_name}.duckdb&quot;)<br><br># let&#39;s see the tables<br>conn.sql(f&quot;SET search_path = &#39;{pipeline.dataset_name}&#39;&quot;)<br>print(&#39;Loaded tables: &#39;)<br>display(conn.sql(&quot;show tables&quot;))<br><br><br>print(&quot;\n\n\n Rides table below: Note the times are properly typed&quot;)<br>rides = conn.sql(&quot;SELECT * FROM rides&quot;).df()<br>display(rides)<br><br>print(&quot;\n\n\n Pasengers table&quot;)<br>passengers = conn.sql(&quot;SELECT * FROM rides__passengers&quot;).df()<br>display(passengers)<br>print(&quot;\n\n\n Stops table&quot;)<br>stops = conn.sql(&quot;SELECT * FROM rides__stops&quot;).df()<br>display(stops)<br><br><br># to reflect the relationships between parent and child rows, let&#39;s join them<br># of course this will have 4 rows due to the two 1:n joins<br><br>print(&quot;\n\n\n joined table&quot;)<br><br>joined = conn.sql(&quot;&quot;&quot;<br>SELECT *<br>FROM rides as r<br>left join rides__passengers as rp<br>  on r._dlt_id = rp._dlt_parent_id<br>left join rides__stops as rs<br>  on r._dlt_id = rs._dlt_parent_id<br>&quot;&quot;&quot;).df()<br>display(joined)</pre><p>We can noticed that the datatypes of time columns have changed from string to timestamp in the database while the nested dictionary got flattened into the parent row, where {&quot;time&quot;:{&quot;pickup&quot;:...}} becomes time__pickup as follow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*-EjFdBs9ExoSRAdwogpkFQ.png" /></figure><p>Besides, the nested lists got broken out into separate tables with generated columns that would allow us to join the data back when needed as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*MaoN6Vy_A8--lsA6Q2qOMA.png" /></figure><p>We can re-join those child tables to the parent table by using the generated keys on parent_table._dlt_id = child_table._dlt_parent_id</p><blockquote>Incremental loading</blockquote><p>Incremental loading refer to the update of our dataset with new data which we only upload the new data rather than making a new copy of source’s data over again to replace the older version. It is <strong><em>expensive </em></strong>and <strong><em>time-consuming. </em></strong>Incremental loading goes hand in hand with incremental extraction and state which is not covered by Adrian in the workshop much due to time-constraint. It can be found <a href="https://dlthub.com/docs/general-usage/state">here</a>.</p><p>dlt now currently supports 2 ways of loading incrementally (<a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/blob/main/cohorts/2024/workshops/dlt_resources/data_ingestion_workshop.md">directly from the Github documentation</a>)</p><ol><li>Append</li></ol><ul><li>We can use this for immutable or stateless events (data that doesn’t change), such as taxi rides — For example, every day there are new rides, and we could load the new ones only instead of the entire history.</li><li>We could also use this to load different versions of stateful data, for example for creating a “slowly changing dimension” table for auditing changes. For example, if we load a list of cars and their colors every day, and one day one car changes color, we need both sets of data to be able to discern that a change happened.</li></ul><p>2. Merge</p><ul><li>We can use this to update data that changes.</li><li>For example, a taxi ride could have a payment status, which is originally “booked” but could later be changed into “paid”, “rejected” or “cancelled”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*IIq3BeuLylIY8cTDlC9C0Q.png" /></figure><p>For example, Adrian showed us the change that have been made by the passengers who gave bad rating and cancelled its payment can be updated using dlt library using “replace” approaches.</p><p>The data:</p><pre>data = [<br>    {<br>        &quot;vendor_name&quot;: &quot;VTS&quot;,<br>    &quot;record_hash&quot;: &quot;b00361a396177a9cb410ff61f20015ad&quot;,<br>        &quot;time&quot;: {<br>            &quot;pickup&quot;: &quot;2009-06-14 23:23:00&quot;,<br>            &quot;dropoff&quot;: &quot;2009-06-14 23:48:00&quot;<br>        },<br>        &quot;Trip_Distance&quot;: 17.52,<br>        &quot;coordinates&quot;: {<br>            &quot;start&quot;: {<br>                &quot;lon&quot;: -73.787442,<br>                &quot;lat&quot;: 40.641525<br>            },<br>            &quot;end&quot;: {<br>                &quot;lon&quot;: -73.980072,<br>                &quot;lat&quot;: 40.742963<br>            }<br>        },<br>        &quot;Rate_Code&quot;: None,<br>        &quot;store_and_forward&quot;: None,<br>        &quot;Payment&quot;: {<br>            &quot;type&quot;: &quot;Credit&quot;,<br>            &quot;amt&quot;: 20.5,<br>            &quot;surcharge&quot;: 0,<br>            &quot;mta_tax&quot;: None,<br>            &quot;tip&quot;: 9,<br>            &quot;tolls&quot;: 4.15,<br>      &quot;status&quot;: &quot;cancelled&quot;<br>        },<br>        &quot;Passenger_Count&quot;: 2,<br>        &quot;passengers&quot;: [<br>            {&quot;name&quot;: &quot;John&quot;, &quot;rating&quot;: 4.4},<br>            {&quot;name&quot;: &quot;Jack&quot;, &quot;rating&quot;: 3.6}<br>        ],<br>        &quot;Stops&quot;: [<br>            {&quot;lon&quot;: -73.6, &quot;lat&quot;: 40.6},<br>            {&quot;lon&quot;: -73.5, &quot;lat&quot;: 40.5}<br>        ]<br>    },<br>]</pre><p>The data can be updated using code below:</p><pre># define the connection to load to.<br># We now use duckdb, but you can switch to Bigquery later<br>pipeline = dlt.pipeline(destination=&#39;duckdb&#39;, dataset_name=&#39;taxi_rides&#39;)<br><br># run the pipeline with default settings, and capture the outcome<br>info = pipeline.run(data,<br>          table_name=&quot;rides&quot;,<br>          write_disposition=&quot;replace&quot;,<br>                    primary_key=&#39;record_hash&#39;)</pre><p>Upon query in DuckDB:</p><pre>conn = duckdb.connect(f&quot;{pipeline.pipeline_name}.duckdb&quot;)<br><br>rides = conn.sql(&quot;SELECT * FROM rides&quot;).df()<br>display(rides)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*6b5ZpfcDSa_eZBO_jcoDVg.png" /></figure><p>The payment status now is in cancelled as shown in the query result.</p><blockquote>End</blockquote><p>Here, i stopped my notes on the first workshop in Data Engineering Zoomcamp 2024, that given by <a href="https://www.linkedin.com/in/data-team/">Adrian</a>. If you’re interested, check out my <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY">Github repo</a> as well🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44801b3dee87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Warehouse & BigQuery ]]></title>
            <link>https://medium.com/@kangzhiyong1999/data-warehouse-bigquery-4d4a281943cd?source=rss-c73ee2584865------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d4a281943cd</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[bigquery-ml]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Kang Zhi Yong]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 06:37:06 GMT</pubDate>
            <atom:updated>2024-02-03T06:37:06.090Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Notes on </em><a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/tree/main/03-data-warehouse"><em>DE Zoomcamp 2024 Module 3: Data </em>Warehouse &amp; BigQuery</a> 🏭</p><blockquote>OLAP vs OLTP</blockquote><p>In data engineering, there are two major concept on which are Online analytical processing (OLAP) and Online Transaction Processing (OLTP) which serve difference purpose in an organisation. The table below summarise the difference between this two concept relatively well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*2qFV_eqCts17vPJdVE6bmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*FKW_m0LzTb2lEYmwg5_DNw.png" /></figure><p>In short, OLTP is more productive for daily transactional functionality which having a connection between an end-user and the application offered by an organisation itself. In contrast, OLAP serve the organisation well in understanding customer needs and even spending behaviour through in-depth data analysis.</p><blockquote>So, What is Data Warehouse?</blockquote><p>Data warehouse is known to be an OLAP solution that widely used for organisation where the data from the sources are cleaned and transformed in <em>staging area</em>, before being loaded here for reporting and data analysis purpose. Taking a step further, the data processed in the data warehouse can be served into <em>Data Marts</em>, which a smaller database sytem that used for different teams within an organisation as shown in flow chart below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*BL9VNXVePXjlH-Fl" /></figure><blockquote>What is BigQuery?</blockquote><p>BigQuery is a serverless data warehouse solution offered by Google Cloud Platform which organisation doesn’t need to taking care of the infrastructure that process the data, offer a relatively fast service in reporting within an organisation. Below are some key features by BigQuery</p><ul><li>Serverless. There are no servers to be managed or databased software to be installed by the organisation itself.</li><li>The software and the infrastructure itself is scalable and in high availability.</li><li>It includes built-in features that support machine learning, geospatial analysis and business intelligence.</li><li>It maximised flexibility by separating the compute engine and storage that stored your data.</li></ul><blockquote>Pricing in BigQuery</blockquote><p>In general, pricing in BigQuery is composed of two main components, which are the compute pricing and storage pricing.The details pricing information can be found in <a href="https://cloud.google.com/bigquery/pricing#storage">Google Cloud website</a> . In regards to this, it is rather important to have a deep understanding in the organisation needs and select the right pricing models. You don’t want to waste your money and resources.</p><p>The compute pricing models can be classified into two:</p><ul><li>On demand pricing (per TiB). You’re charged for the number of bytes processed by each query. The first 1 TiB of query data processed per month is free. To date, the pricing is $6.25 per TiB.</li><li>Capacity pricing (per slot-hour). You’re charged for compute capacity used to run queries, measured in slots (virtual CPUs) over time. This model takes advantage of <a href="https://cloud.google.com/bigquery/docs/editions-intro">BigQuery editions</a>, which are the standard, enterprise and enterprise plus edition.</li></ul><p>Storage pricing then can be divided into two classes as well, the active logical storage ($0.02 per GiB per month) and long-term logical storage ($0.01 per GiB per month).</p><p>An approximation of the size of the data being processed will be shown in the right corner of the window prior running running queries on BigQuery. It might give you a glance on how many bytes of data will be processed by the particular execution. The actual amount of processed data will then appear in the <em>Query results</em> panel in the lower half of the window. It might be helpful to quickly calculate and optimise the cost of the query for your project.</p><blockquote>Creating an external table in BigQuery</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBIOPGzq-1NKcBL23Lxwlg.jpeg" /></figure><p>BigQuery support the external data sources, although the data is not stored in the BigQuery strorage. For instance, it can direcly queried from data stored in Google Cloud Storage upon creation of external table.</p><p><em>External table </em>is a table than function like standard BigQuery table with table schema is stored in BQ but data itself is external. No preview of data is available in that sense. You might create an external table from a .csv or .parquet file from Google Cloud Storage in this way:</p><pre> -- Creating external table referring to gcs path<br>CREATE OR REPLACE EXTERNAL TABLE `de-zoomcamp-412301.ny_taxi.external_yellow_tripdata` <br>OPTIONS ( format = &#39;parquet&#39;,<br>    uris = [&#39;gs://module-3-zoomcamp/yellow/yellow_tripdata_2020-*.parquet&#39;,<br>    &#39;gs://module-3-zoomcamp/yellow/yellow_tripdata_2019-*.parquet&#39;]);<br></pre><p>Be aware of that the estimation of bytes of data for the query from external table is not available. In regards to that, you can import external table in BQ as regular table. For example:</p><pre>CREATE OR REPLACE TABLE `de-zoomcamp-412301.nytaxi.yellow_tripdata_non_partitoned` AS<br>SELECT * FROM `de-zoomcamp-412301.nytaxi.external_yellow_tripdata`;</pre><blockquote>Partitioning</blockquote><p>The BigQuery table can be partitioned into smaller tables which improve the query performance, thus saving cost. For instances, if we often query the data by date, we then can further partition our table by date, hence we can do a sub-query based on the date we are particularly interested in. In general, you can partition a table by:</p><ol><li>Time-unit column like Timestamp , Date or Datetime column in a table</li><li>Ingestion time. The timestamp where the data is ingested to BigQuery</li><li>Integer range partitioning</li><li>The default partition is daily wile using time unit and ingestion time. It can be changed to hourly , monthly or even yearly</li></ol><p>Here is the example of partitioning data by datetime column,</p><pre>-- Create a partitioned table from external table<br>CREATE OR REPLACE TABLE de-zoomcamp-412301.ny_taxi.yellow_tripdata_partitoned<br>PARTITION BY<br>  DATE(pickup_date) AS<br>SELECT * FROM de-zoomcamp-412301.ny_taxi.external_yellow_tripdata_corrected;</pre><p>This partition have then cut down the bytes of data being scanned when we are doing the query, comparing between non-partitioned and partitioned table</p><pre>-- Impact of partition<br>-- Scanning 1.6GB of data<br>SELECT DISTINCT(VendorID)<br>FROM de-zoomcamp-412301.ny_taxi.yellow_tripdata_non_partitoned<br>WHERE DATE(pickup_date) BETWEEN &#39;2019-06-01&#39; AND &#39;2019-06-30&#39;;<br><br>-- Scanning ~106 MB of DATA<br>SELECT DISTINCT(VendorID)<br>FROM de-zoomcamp-412301.ny_taxi.yellow_tripdata_partitoned<br>WHERE DATE(pickup_date) BETWEEN &#39;2019-06-01&#39; AND &#39;2019-06-30&#39;;</pre><p>You may also check the rows of each partitions with query as follow</p><pre>-- Let&#39;s look into the partitons<br>SELECT table_name, partition_id, total_rows<br>FROM `ny_taxi.INFORMATION_SCHEMA.PARTITIONS`<br>WHERE table_name = &#39;yellow_tripdata_partitoned&#39;<br>ORDER BY total_rows DESC;</pre><p>The query above give you a quick view on how the partitions look like your table. Note that the partitions limit is 4000. The figure below show how the partitioning in BQ look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*0MiVQ325aJs9-Nba" /></figure><blockquote>Clustering</blockquote><p>Clustering is another technique to cut down processing time by query on the right chunk of data. Is is achieved by selecting the columns which used to colocate the related data, up to 4 columns can be chosen for clustering . The order of column is important as it kind of sorting out the order of the data. For instance, kindly refer to the figure below which dataset is first partitioned using date column then clustered by Tags . In regards to this, it significantly improve the quering time of filter queries as well as aggregate queries. However, it is important to note that is <em>doesn’t show significant improvement </em>on partitioning and clustering if the table is size <em>below than 1GB</em>. Clustering columns must be top-level, non-repeated columns. The available data type for clustering include: DATE , BOOL , GEOGRAPHY , INT64 , NUMERIC , BIGNUMERIC , STRING , TIMESTAMP , DATETIME .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8a0YMpneAaU09MOG" /></figure><p>Taking example that used in the module, the partitioning and clustering can be performed together as follow:</p><pre>-- Creating a partition and cluster table<br>CREATE OR REPLACE TABLE de-zoomcamp-412301.ny_taxi.yellow_tripdata_partitoned_clustered<br>PARTITION BY DATE(pickup_date)<br>CLUSTER BY VendorID AS<br>SELECT * FROM de-zoomcamp-412301.ny_taxi.external_yellow_tripdata_corrected;</pre><p>In result of that, the total byte of query has been cut down from 1.1GB to 864.5MB of data in Table.</p><pre>-- Query scans 1.1 GB<br>SELECT count(*) as trips<br>FROM de-zoomcamp-412301.ny_taxi.yellow_tripdata_partitoned<br>WHERE DATE(pickup_date) BETWEEN &#39;2019-06-01&#39; AND &#39;2020-12-31&#39;<br>  AND VendorID=1;<br><br><br>-- Query scans 864.5 MB<br>SELECT count(*) as trips<br>FROM de-zoomcamp-412301.ny_taxi.yellow_tripdata_partitoned_clustered<br>WHERE DATE(pickup_date) BETWEEN &#39;2019-06-01&#39; AND &#39;2020-12-31&#39;<br>  AND VendorID=1;</pre><blockquote>Partitioning vs Clustering</blockquote><p>Although clustering and partitioning can be used concurrently. However, there are still difference to be noted when designing and performing our queries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*U4ZYi8EoNJhHXnw5ys92Kg.png" /></figure><p>Clustering might be favoured in few conditions:</p><ul><li>When the partitioning result in a small amount of data per partition (less than 1GB)</li><li>Partitioning results in large number of partitioned table, exceeding 4000</li><li>Partitioning results in your mutation operations modifying the majority of partitions in table frequently (every few minutes).</li></ul><p>Aside from that, BigQuery adopted <em>automatic reclustering</em>. When new data is added to the clustered table, it perform the automatic re-clusteirng in the background to restore the sort property of the tbale and the newly inserted data can be written to blocks that contain key ranges that overlap with ist previously written blocks. For partitioned table, re-clustering is donw within the scope of each partition.</p><blockquote>Best Practice in BigQuery</blockquote><p>Cost reduction</p><ul><li>Avoid SELECT *</li><li>Price your queries before running them</li><li>Use clustered or partitioned tables</li><li>Use streaming inserts with caution</li><li>Materialize query results in stages</li></ul><p>Query Performance</p><ul><li>Filter on partitioned columns</li><li>Denormalizing data</li><li>Use nested or repeated columns</li><li>Use external data sources appropriately</li><li>Don’t use it, in case u want a high query performance</li><li>Reduce data before using a JOIN</li><li>Do not treat WITH clauses as prepared statements</li><li>Avoid overshading tables</li><li>Avoid JavaScript user-defined functions</li><li>Use approximate aggregation functions (HyperLogLog++)</li><li>Order Last, for query operations to maximize performance</li><li>Optimize your join patterns. Place the table with the largest number of rows first, followed by the table with the fewest rows, and then place the remaining tables by decreasing size</li></ul><blockquote>Internal Infrastructure of BigQuery</blockquote><p>It is not necessary to know the internal structure of BigQuery, but it might give us a more intuitive way to understand how our query is being executed behind the scene. In general, BigQuery is composed of 4 main parts, namely Colossus, Jupiter, Dremel and Borg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*fL9C5Z1RzVC_im4I" /></figure><ul><li><em>Colossus</em>: A cheap storage that stores data in a columnar format that separated from the compute cluster.</li><li><em>Jupiter</em>: A Google in-house network to connect between colossus and compute engine with a 1TiB network speed, ensuring low latency.</li><li><em>Dremel</em>: Query execution engine, which divide query into tree structure, thus each nodes can execute individual subset of the query.</li><li><em>Borg</em>: an orchestration solution that handles everything.</li></ul><p>Comparing between the column-oriented and record-oriented storage, both of them serve the different purpose in data science. In the record-oriented storage, it is more likely to be in .csv file structure which every new line is the new records for an observation. It is relatively easy to understand. In contrast, the column-oriented storage. The data is stored in column rather than rows. It is very beneficial for query efficiency as it allow us to discard right away the columns that we’re not looking file, reducing the amount that we have to process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/0*B3GLNLkn-DtSO0pA" /></figure><p>In <em>dermel</em>, the SQL query engine will take in a query, then further divide the query into mixer where the query is modified and bring to leaf node. At leaf nodes, this is the layer which connect to the<em> colossus </em>to fetch the data for appropriate operation on top of that, then return to mixer, then root server where data is aggregated and return to user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*SuzagrDyceTpkAZ5" /></figure><p>More information on internal structure of BigQuery can be found in link below:</p><ul><li><a href="https://cloud.google.com/bigquery/docs/how-to">https://cloud.google.com/bigquery/docs/how-to</a></li><li><a href="https://research.google/pubs/pub36632/">https://research.google/pubs/pub36632/</a></li><li><a href="https://panoply.io/data-warehouse-guide/bigquery-architecture/">https://panoply.io/data-warehouse-guide/bigquery-architecture/</a></li><li><a href="http://www.goldsborough.me/distributed-systems/2019/05/18/21-09-00-a_look_at_dremel/">http://www.goldsborough.me/distributed-systems/2019/05/18/21-09-00-a_look_at_dremel/</a></li></ul><blockquote>Machine Learning in BigQuery</blockquote><p>In BigQuery, suprisingly it also offer the machine learning feature with target audience of Data Analyst and manager with no prior knowledge on Python or Java Knowledge. It can be directly done in BigQuery without exporting the data into different system. The figure below show the ML that offered in the BigQuery. For its pricing, the details can be refer to the website <a href="https://cloud.google.com/bigquery/pricing">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Y0a95orooRkkQq6U" /></figure><p>We will now go through a simple ML model using the New York taxi dataset by first creating a custom table.</p><pre>-- CREATE A ML TABLE WITH APPROPRIATE TYPE<br>CREATE OR REPLACE TABLE `de-zoomcamp-412301.ny_taxi.yellow_tripdata_ml` (<br>`passenger_count` INTEGER,<br>`trip_distance` FLOAT64,<br>`PULocationID` STRING,<br>`DOLocationID` STRING,<br>`payment_type` STRING,<br>`fare_amount` FLOAT64,<br>`tolls_amount` FLOAT64,<br>`tip_amount` FLOAT64<br>) AS (<br>SELECT passenger_count, trip_distance, cast(PULocationID AS STRING), CAST(DOLocationID AS STRING),<br>CAST(payment_type AS STRING), fare_amount, tolls_amount, tip_amount<br>FROM `de-zoomcamp-412301.ny_taxi.yellow_tripdata_partitoned` WHERE fare_amount != 0<br>);<br></pre><ul><li>BigQuery supports feature preprocessing</li><li>Columns such as PULocationID which is categorical data, represented with integer numbers in the original table are changed to be string, thus the BigQuery can one-hot encoded into categorical featueres.</li><li>Our target feature for the model will be tip_amount. We drop all records where tip_amount equals zero to ensure dataset quality.</li></ul><p>Then, we create a Linear Regression Model with default hyper-parameters</p><pre>-- CREATE MODEL WITH DEFAULT SETTING<br>CREATE OR REPLACE MODEL `de-zoomcamp-412301.ny_taxi.tip_model`<br>OPTIONS<br>(model_type=&#39;linear_reg&#39;,<br>input_label_cols=[&#39;tip_amount&#39;],<br>DATA_SPLIT_METHOD=&#39;AUTO_SPLIT&#39;) AS<br>SELECT<br>*<br>FROM<br>`de-zoomcamp-412301.ny_taxi.yellow_tripdata_ml`<br>WHERE<br>tip_amount IS NOT NULL;</pre><ul><li>The OPTIONS() clause allow us to choose the model used for training, which linear_reg , denoting linear regression while input_label_cols denote the column that we trained our dataset to predict, which is the tip_amount in thie case. The AUTO_SPLIT then automatically split our data into train and test set.</li></ul><p>After running the query, the trained model will be available in the explorer side panel of BigQuery. By running the SQL query below, we can then check the features used in the training of model.</p><pre><br>-- CHECK FEATURES<br>SELECT * FROM ML.FEATURE_INFO(MODEL `de-zoomcamp-412301.ny_taxi.tip_model`);</pre><p>We then can evaluate the performance of our model against another dataset via</p><pre>-- EVALUATE THE MODEL<br>SELECT<br>*<br>FROM<br>ML.EVALUATE(MODEL `de-zoomcamp-412301.ny_taxi.tip_model`,<br>(<br>SELECT<br>*<br>FROM<br>`de-zoomcamp-412301.ny_taxi.yellow_tripdata_ml`<br>WHERE<br>tip_amount IS NOT NULL<br>));</pre><p>where the root means square and Pearson correlation will be calculated. The next step in ML is to predict the target using dataset. In our modules, we will be using back the same dataset used for training for demonstration purpose. In real case, it is normally tested with dataset that is not previously used for training. This could be achieved via</p><pre>-- PREDICT THE MODEL<br>SELECT<br>*<br>FROM<br>ML.PREDICT(MODEL `de-zoomcamp-412301.ny_taxi.tip_model`,<br>(<br>SELECT<br>*<br>FROM<br>`de-zoomcamp-412301.ny_taxi.yellow_tripdata_ml`<br>WHERE<br>tip_amount IS NOT NULL<br>));</pre><p>Upon the prediction, you might wonder how to explain the model using the key features which influence the most in our model. To extract those feature, we can run a SQL query like</p><pre>-- PREDICT AND EXPLAIN<br>SELECT<br>*<br>FROM<br>ML.EXPLAIN_PREDICT(MODEL `de-zoomcamp-412301.ny_taxi.tip_model`,<br>(<br>SELECT<br>*<br>FROM<br>`de-zoomcamp-412301.ny_taxi.yellow_tripdata_ml`<br>WHERE<br>tip_amount IS NOT NULL<br>), STRUCT(3 as top_k_features));</pre><p>In ML, the improvement of model performance can be achieved by hyper-parameter tuning. In BigQuery, similar strategy can be done via</p><pre>-- HYPER PARAM TUNNING<br>CREATE OR REPLACE MODEL `de-zoomcamp-412301.ny_taxi.tip_hyperparam_model`<br>OPTIONS<br>(model_type=&#39;linear_reg&#39;,<br>input_label_cols=[&#39;tip_amount&#39;],<br>DATA_SPLIT_METHOD=&#39;AUTO_SPLIT&#39;,<br>num_trials=5,<br>max_parallel_trials=2,<br>l1_reg=hparam_range(0, 20),<br>l2_reg=hparam_candidates([0, 0.1, 1, 10])) AS<br>SELECT<br>*<br>FROM<br>`de-zoomcamp-412301.ny_taxi.yellow_tripdata_ml`<br>WHERE<br>tip_amount IS NOT NULL;</pre><p>We included more parameter in the OPTIONS() clause to define number of trials, L1 regression and etc.</p><blockquote>ML deployment from BigQuery</blockquote><p>ML models created can be exported to Google Cloud Storage and deployed to Docker containers with TensorFlow Serving running. You can check out the official documentation of deployment <a href="https://cloud.google.com/bigquery/docs/export-model-tutorial">here</a> or <a href="https://www.youtube.com/watch?v=BjARzEWaznU">tutorials</a> in the module. The steps for deployment is also documented in the <a href="https://github.com/DataTalksClub/data-engineering-zoomcamp/blob/main/03-data-warehouse/extract_model.md">Github repository</a>.</p><blockquote>End</blockquote><p>Here, i stopped my notes on module 3 for Data Engineering Zoomcamp 2024, the figure used is by DataTalksClub, available <a href="https://docs.google.com/presentation/d/1a3ZoBAXFk8-EhUsd7rAZd-5p_HpltkzSeujjRGB2TAI/edit#slide=id.g10c8bcef47f_0_50">here</a>. If you’re interested, check out my <a href="https://github.com/10Kang/DE_Zoomcamp2024_ZY/tree/main/module_3_data_warehouse_bigquery">Github repo</a> 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d4a281943cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>