<?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 Thomas Thomas on Medium]]></title>
        <description><![CDATA[Stories by Thomas Thomas on Medium]]></description>
        <link>https://medium.com/@thomaspt748?source=rss-959b8306437------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D0HnnXkNmj76Twd_NFaSKQ.jpeg</url>
            <title>Stories by Thomas Thomas on Medium</title>
            <link>https://medium.com/@thomaspt748?source=rss-959b8306437------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:59:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thomaspt748/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[How to Flatten Json Files Dynamically Using Apache Spark(Scala Version)]]></title>
            <link>https://medium.com/@thomaspt748/how-to-flatten-json-files-dynamically-using-apache-spark-scala-version-9cc9560631dd?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc9560631dd</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 04:14:40 GMT</pubDate>
            <atom:updated>2022-03-02T04:14:40.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQ2zhD518510aXnlCp7Qug.png" /></figure><p>There are several file types are available when we look at the use case of ingesting data from different sources. Some of them are Parquet, Avro, ORC, CSV, JSON, XML..etc. Json is the most commonly used file type when designing a data service or data streaming integration pattern for data engineering work.</p><p>A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. JSON files are lightweight, text-based, human-readable, and can be edited using a text editor.</p><p>We all had to deal with the use case of flattening Json using Spark in the data engineering world at least once. I had multiple use cases in the past to flatten 100+ Jsons from different data sources. Rather than writing code for flattening each Json, started looking for a generic function to flatten any Json with any levels of nesting, which would save a lot of time. My search for the generic function motivated me to write this article.</p><p>Spark provides many functions to handle Jsons. The two most commonly used ones are <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.explode.html#pyspark.sql.functions.explode">Explode</a> and <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.explode_outer.html#pyspark.sql.functions.explode_outer">Explode_outer</a> functions.</p><p>All source code in this article is written in Scala and Spark ver 2.4.0. This article is code-oriented and self-explanatory. However, I will provide some explanations as we flow through the code. Now, let’s Open our favorite IDE and start coding…</p><blockquote><strong>Step1:Download a Sample nested Json file for flattening logic.</strong></blockquote><p><a href="https://opensource.adobe.com/Spry/samples/data_region/JSONDataSetSample.html#Example5">JSON Data Set Sample</a></p><blockquote><strong>Step2: Create a new scala object called </strong>FlatJson <strong>and write functions for flattening Json.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1R2IfCKuZP8PaK-m5dlt7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMeTJNETJMe-hAJjiAG3bQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGl7wewXaa6O9T-wzjecFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfdpki4KRqPcv1Dz3kevOA.png" /></figure><blockquote><strong>Step3: Initiate Spark Session.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*we8FajoxQ6NSKi2clCEIxw.png" /></figure><blockquote><strong>Step4:Create a new Spark DataFrame using the sample Json.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmC2iv6hqViMyBsDglephg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVXvLua-nKKMYb5l8HZyxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsRjXAdE_GcZpbTQwe-2pA.png" /></figure><p>The output of the above data frame is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1foZ6zdbvWUVkpJI7f0BA.png" /></figure><blockquote><strong>Step5: Flatten Json in Spark DataFrame using the above function.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB6KkT9ocOoRxbPFbc9pqQ.png" /></figure><p>When you execute the program you will get a flattened Spark DataFrame as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAt_95iGtbjKCO-8d6kBEw.png" /></figure><p>The program marks each level of json with *1, *2 like that.. and “-&gt;” shows the child node of a parent node.</p><p>I have tested the program with many complex Json and so far every Json flattened successfully. However the program is still in the beta testing mode, so please test thoroughly for your use case before using this code in an actual production environment.</p><p>Make sure you have appropriate Spark partitions when you deal with large data sets.</p><p>“Happy Coding…”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc9560631dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to UPSERT data into a relational database using Apache Spark: Part 2 (Python Version)]]></title>
            <link>https://medium.com/@thomaspt748/how-to-upsert-data-into-a-relational-database-using-apache-spark-part-2-python-version-da30352c0ca9?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/da30352c0ca9</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 02:59:38 GMT</pubDate>
            <atom:updated>2022-02-15T02:59:38.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QrVajF6HOLsrleAv.png" /></figure><p>In my opinion, Database UPSERT won’t be complete without talking about MERGE functionality. In this blog, we will sail through how we can UPSERT using the MERGE command.</p><p>SELECT from a database table and then INSERT or UPDATE based on the condition are the traditional way of handling data UPSERT. With the MERGE statement, you can combine those statements into a single one and improve the overall performance of the individual transaction.</p><p>Most of the relational databases support the MERGE command. In the Part 1 example, I’ve used MySQL. But MERGE is not supported by MySQL, However, there is a different way of achieving the same in MySQL:</p><p><a href="https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html">INSERT…ON DUPLICATE KEY UPDATE</a></p><blockquote>If you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement and the new row causes a duplicate value in the UNIQUE or PRIMARY KEY index, MySQL performs an update to the old row based on the new values.</blockquote><p>In this example, I’m going to use the PostgreSQL database and INSERT ON CONFLICT statement. Following is a syntax diagram for the INSERT statement showing all of its principal clauses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUxgDNwckWMWss6vmQ6Qnw.png" /></figure><p>In its simplest form the INSERT ON CONFLICT statement looks like this:</p><pre>INSERT INTO table_name(column_list)  <br>VALUES(value_list) <br>ON CONFLICT<br>DO<br>  UPDATE Statement;</pre><p>Let’s re-write <strong>Step 4.4</strong> in Part 1 example using the INSERT ON CONFLICT command.</p><p><strong>4. Update database table records using Spark.</strong></p><p>For our example let’s say the school city <strong>“Abilene”</strong> is changed to <strong>“NewYork”</strong> and <strong>“University of Akron, University of Alabama” is </strong>changed to “<strong>Albany State University”.</strong></p><p>Let&#39;s see how this is updated into the school table.</p><p>Step 4.1: Get the data from CSV file to update the school table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9D1yDnCI5TFBcw9TdW5Cg.png" /></figure><p>Step 4.2: Setup JDBC connection parameters. Please note that I’ve modified the connection parameter to suit the PostgreSQL database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRRXYkRjahG_VTmyb_m6ZA.png" /></figure><p>Step 4.3: Broadcast JDBC connection parameters to cluster nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLZo34kZatwCSZ1thCll8Q.png" /></figure><p>Step 4.4: Create a function <strong>process_row </strong>to process each row in the partition .The function execute an INSERT ON CONFLICT statement using the key column value to check whether the spark dataframe row exists in the database.If the row exists, executes an UPDATE statement and if a row does not exist, create an INSERT statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lOX01bIN5RpIWT-PqjRaw.png" /><figcaption>Function: process_row</figcaption></figure><p>Step 4.5: Create a function <strong>process_partition </strong>to process each partition in the dataframe. The function establishes a PostgreSQL database connection and process all rows in the current partition using <strong>process_row</strong> function and commit all changes in that partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpXpBAV3CciS4IlTFvfWmw.png" /><figcaption>Function process_partition</figcaption></figure><p>Step 4.6: Browse through each partitioned data and process each partition using <strong>process_partition</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ORCAGAoAHiXCJIceZBheg.png" /></figure><p>In the above example Coalesce is used. You can use repartition also.</p><blockquote>On a side note, here is the difference between coalesce and repartition</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld15_a2h9Ng03hOlkr9H8A.png" /></figure><p>I didn’t get a chance to benchmark this time. Based on my previous benchmarking exercise, I beleive INSERT ON CONFLICT statements should perform better than the traditional SELECT/and UPDATE/INSERT.</p><p>Happy Coding…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da30352c0ca9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to UPSERT data into a relational database using Apache Spark: Part 1(Python Version)]]></title>
            <link>https://medium.com/@thomaspt748/how-to-upsert-data-into-a-relational-database-using-apache-spark-part-1-python-version-b43b9761bbf2?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/b43b9761bbf2</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hadoop]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 05:44:00 GMT</pubDate>
            <atom:updated>2022-02-15T03:02:23.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*AkyYnKokIgk2iqChKydHKQ.png" /></figure><p>Apache Spark has multiple ways to read data from different sources like files, databases, etc. But when it comes to loading data into RDBMS(relational database management system), Spark supports only Append and Overlay of the data using dataframes. Spark dataframes do not support Updating of data into a database.</p><p>However, I had come across several business use cases where I had to update the data. It was a challenge to handle the scenario when I was faced with updating the data using Spark and I thought I will share with you my learning experience and how I solved this issue.</p><p>In this blog, we will explore how we can update the RDBMS data using Spark without losing the power of Spark. I’m using <strong>python</strong> language to execute my spark code. Let’s look at an example of reading a sample CSV file with school data and <strong>Upserting</strong> the school data into a school table using Spark data frame.</p><ol><li><strong>Read data from a CSV file</strong></li></ol><p>When we read a <strong>CSV</strong> file or text file data using Spark libraries the output value will be an actual spark data frame. Spark parallelizes the data and puts data into multiple partitions as it reads the data from a file into a data frame. As you know data frame doesn’t contain data until we perform an action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hSMhiqna_Uelpp-t3ePZg.png" /></figure><p>When we execute the above code, the output will be something similar to the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_H5WOg4JLIM2BQh2uCwfQ.png" /><figcaption>Fig 1. School data from csv file in a Spark Dataframe</figcaption></figure><p><strong>2. Create a database schema and table in MySQL DB.</strong>(This step can be skipped if you already have a database table)</p><p>You can use any relational database(that can connect using JDBC) to load data. In this example, I’m using MySQL DB as the target database. And target table name is <strong>school</strong>.</p><p>Step 1: Log in to MySQL workbench.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Tn91WXsWo3sZWqGhsgx_dA.png" /></figure><p>Step 2: Create a new schema named <strong>myDB.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*gun2OT5UQDZ17QaSA0T6cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*DJgrlx8Y9rTW0i7GJKUAXQ.png" /></figure><p>myDB schema is created as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*4TlRQ-C86QGuRHlSUC1Q6A.png" /></figure><p>Step 3: Create a new table <strong>School </strong>in myDB schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*FNQS8DqVR70e9f794wyXzw.png" /></figure><p><strong>3. Load spark dataframe data into a database.</strong></p><p>In order to load the data into a database table, you need to make sure that the dataframe column names and data types match exactly to the column names and datatypes of the target database table. Otherwise, it will give an error as below.</p><p>“Exception in thread “main” org.apache.spark.sql.AnalysisException:”</p><p>Now let’s load the above dataframe data(in Fig 1.) into the <strong>school</strong> table. See the code snippet below to load the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8sQxj-D2FmFl6BkCfuCn7A.png" /></figure><p>In the above code <strong>dfCsv.write</strong> function will write the content of the dataframe into a database table using the JDBC connection parameters.</p><p>When writing dataframe data into a database spark uses the <strong>saveMode</strong> to specify the expected behavior of saving a DataFrame to a data source. There are four save modes in Spark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRxOi2rkxxdNsLIaeB0OGw.png" /></figure><p>Okay, Now let’s retrieve the data from the school table to ensure that the data is loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8zCZG7Tf0p9ywXSnNfKug.png" /></figure><p>When you run the above code, <strong>schoolDf.show</strong> will give the output as displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1sSIP3TeO_wCTuwFl-ZDQ.png" /></figure><p><strong>4. Update database table records using Spark.</strong></p><p>For our example let’s say the school city <strong>“Abilene”</strong> is changed to <strong>“NewYork”</strong> and <strong>“University of Akron, University of Alabam” is </strong>changed to “<strong>Albany State University”.</strong></p><p>Let&#39;s see how this is updated into the school table.</p><p>Step 4.1: Get the data from a CSV file to update the school table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hSMhiqna_Uelpp-t3ePZg.png" /></figure><p>When you run the above code you can see that(output below)the CSV file data is changed as we menioned in step 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhw2GyvENFGgCfMKOjhulQ.png" /></figure><p>Step 4.2: Setup mysql connection parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TA6Hx2mZQruJWBriDr_pQA.png" /></figure><p>Step 4.3: Broadcast mysql connection parameters to cluster nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqQdyMAQKuEGoopZScRwrw.png" /></figure><p>Step 4.4: Create a function <strong>process_row </strong>to process each row in the partition .The function execute a SELECT statement using the key column value to check whether the spark dataframe row exists in the database.If the row exists, generate an UPDATE statement and if a row does not exist, create an INSERT statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwW-BqYrHgDb2b8lD996AA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89Orti0lsbJwhGx4f38Vyg.png" /><figcaption>Function process_row</figcaption></figure><p>Step 4.5: Create a function <strong>process_partition </strong>to process each partition in the dataframe. The function establishes a mysql database connection and process all rows in the current partition using <strong>process_row</strong> function and commit all changes in that partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-oRrbJI8jkOi8YgHOW9BA.png" /><figcaption>Function process_partition</figcaption></figure><p>Step 4.6: Browse through each partitioned data and process each partition using <strong>process_partition</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSxGIGdNzw1jwbFe-KMF4A.png" /></figure><p>If you noticed I have commit the data for each partition level.</p><p>SELECT, INSERT, and UPDATE are the traditional way of handling data UPSERT. Database UPSERT won&#39;t be complete without talking about merge functionality. <a href="https://medium.com/@thomaspt748/how-to-upsert-data-into-a-relational-database-using-apache-spark-part-2-python-version-da30352c0ca9">Please continue to read Part 2 for the merge statement….</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b43b9761bbf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Flatten Json Files Dynamically Using Apache PySpark(Python)]]></title>
            <link>https://medium.com/@thomaspt748/how-to-flatten-json-files-dynamically-using-apache-pyspark-c6b1b5fd4777?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b1b5fd4777</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 04:41:23 GMT</pubDate>
            <atom:updated>2022-03-02T03:49:02.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQ2zhD518510aXnlCp7Qug.png" /></figure><p>There are several file types are available when we look at the use case of ingesting data from different sources. Some of them are Parquet, Avro, ORC, CSV, JSON, XML..etc. Json is the most commonly used file type when designing a data service or data streaming integration pattern for data engineering work.</p><p>A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which is a standard data interchange format. JSON files are lightweight, text-based, human-readable, and can be edited using a text editor.</p><p>We all had to deal with the use case of flattening Json using Spark in the data engineering world at least once. I had multiple use cases in the past to flatten 100+ Jsons from different data sources. Rather than writing code for flattening each Json, started looking for a generic function to flatten any Json with any levels of nesting, which would save a lot of time. My search for the generic function motivated me to write this article.</p><p>Spark provides many functions to handle Jsons. The two most commonly used ones are <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.explode.html#pyspark.sql.functions.explode">Explode</a> and <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.functions.explode_outer.html#pyspark.sql.functions.explode_outer">Explode_outer</a> functions.</p><p>All source code in this article is written in Python and Spark(Pyspark ver 3.1.2). This article is code-oriented and self-explanatory. However, I will provide some explanations as we flow through the code. Now, let’s Open our favorite IDE and start coding…</p><blockquote><strong>Step1:Download a Sample nested Json file for flattening logic.</strong></blockquote><p><a href="https://opensource.adobe.com/Spry/samples/data_region/JSONDataSetSample.html#Example5">JSON Data Set Sample</a></p><blockquote><strong>Step2: Create a new python file flatjson.py and write Python functions for flattening Json.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XfIIv384isiPRNen94ruA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AbXFZOJ836fPWqefs0B3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26zsMZdWVUdKcWstQD74MA.png" /></figure><blockquote><strong>Step3: Initiate Spark Session.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoSA4BKSIqNGZj8gBv1LLg.png" /></figure><blockquote><strong>Step4:Create a new Spark DataFrame using the sample Json.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmDZkEJ-i8z8N4R4a7gUxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbxgkuORXLdirqRrvG6mkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh-mHahHsSmGni9ByZH8ng.png" /></figure><p>The output of the above data frame is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ox8zRMm-d_mIlQ6Y-kEs6A.png" /></figure><blockquote><strong>Step5: Flatten Json in Spark DataFrame using the above function.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AiM6WOWlcXuy0VIKeF0jyg.png" /></figure><p>When you execute the program you will get a flattened Spark DataFrame as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*454P-l3Rp6_tjiw5M8ltUQ.png" /></figure><p>The program marks each level of json with *1, *2 like that.. and “-&gt;” shows the child node of a parent node.</p><p>I have tested the program with many complex Json and so far every Json flattened successfully. However the program is still in the beta testing mode, so please test thoroughly for your use case before using this code in an actual production environment.</p><p>Make sure you have appropriate Spark partitions when you deal with large data sets.</p><p>“Happy Coding…”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b1b5fd4777" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate C/C++ Libraries(dll/so) into Apache Spark/Scala in Hadoop Cluster]]></title>
            <link>https://medium.com/@thomaspt748/integrate-c-c-libraries-dll-so-into-apache-spark-scala-in-hadoop-cluster-56cdb26e15ea?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/56cdb26e15ea</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 01:42:31 GMT</pubDate>
            <atom:updated>2020-07-26T01:47:42.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h27DNkhef9GvXotlC-CkQw.png" /></figure><p><strong>C++</strong> is a powerful, efficient and fast language. C/C++ is the backbone of all the well-known operating systems, browsers, Machine learning libraries, cloud distributed systems, databases, embedded systems, compilers, etc. It’s high speed and the fact that it is closer to hardware makes it a preferred choice over other languages.</p><p>As of today we have several applications written in C/C++ and the question is: how do we leverage the power of C++ applications in the Bigdata world?</p><p>In this blog, we will explore how to invoke a C/C++ dynamic library file from Apache Spark. We will be running this in a Spark 2.4.0/Scala 2.11.8/Linux environment, so my library will be a .so file. If you are using Windows you will have a .dll file. DLL is representative of the Windows Dynamic Library and SO is representative of the Linux dynamic library. Both have the same purpose, to be loaded dynamically. Let’s get started.</p><p>In order to prove the concept, let’s create a simple C/C++ library file that has an addition function which accepts two integer parameters and returns the sum of those integer parameters. Then we will invoke the C/C++ library function from Spark worker nodes during cluster computing.</p><h4><strong><em>Step 1: Create a C/C++ shared object file called “Calc.so”.</em></strong></h4><blockquote>a. Create a header file <strong>calc.h.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzCa7su38UswnO03WeVlaQ.png" /></figure><blockquote>b. Create <strong>calc.c </strong>file and <strong>add</strong> function logic inside.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNbxeNwoyK9bacvo_r816Q.png" /></figure><blockquote>c. Compile the c program and create .so file using the following commands.</blockquote><ul><li>gcc -c -Wall -Werror -fpic calc.c</li><li>gcc -shared -o libcalc.so calc.o</li></ul><h4>Step 2: Create a Spark application to call add function of libcalc.so library file.</h4><p>Now that we have created the C/C++ library file calc.so, let’s look at building a Spark Application.</p><p>We will be using Java Native Access(JNA) to load C/C++ library from Scala. Download the jar file “jna-5.6.0.jar” and add to Eclipse/Intellij class path or you can add as a dependency to your pom.xml or build.sbt file as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFhMB2I-DWq62rW6vTeQyw.png" /><figcaption>build.sbt dependency</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZNT37YtkMcUMiVhWJS7yg.png" /><figcaption>POM.xml dependency</figcaption></figure><blockquote>a. Create a scala trait called <strong>libcalc </strong>as below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*qcWPH07pEos91bEZ7nTCoQ.png" /></figure><blockquote>b. Now create a Spark Dataframe and display its data.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*yEgKv3RQ7cUmZn8I-EfOpA.png" /></figure><p>When we execute the above code, the output will be something similar to what is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IX4Icn4ImTVilL6n3keZgA.png" /><figcaption>Output from df.show()</figcaption></figure><blockquote>c. Let’s iterate through the Dataframe’s MapPartitions and load the native C library “libcalc.so” for each partition and call <strong>add</strong> function. In order to use the libcalc.so file , you just need to specify the C/C++ application name which is “calc” in the Native.load function. Note that we are loading the C/C++ libarary as instance of the trait “libcalc” that we created in the previous step.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wTf1EK-jftAWHmEM38sUQ.png" /></figure><h4>Step 3: Run our Spark Application.</h4><p>Now we have the Spark Application created, let’s build the scala jar file and run using Spark-submit command. In this example my application jar file name is “SparkCLib.jar”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pPk7WaRt00GYHtKp74sWQ.png" /></figure><p>After you execute the above command you will get the following output from the newDf.show(). The column named “Sum” is populated from the C/C++ library function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0fl0-rY4pO5HpygCP8rVQ.png" /></figure><p>The spark-submit command option “files” will upload “libcalc.so” file to all spark worker nodes.</p><p><strong><em>Final Thoughts…</em></strong></p><p>You can save the Spark Dataframe into a database or HDFS based on the use case. Some of the options you choose for Spark-submit command may change depending on your cluster setup. Currently, Spark does not support C++ UDF. In my experience, this is the best way to run your C/C++ program in parallel to process your big data needs.</p><p>Happy Coding…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56cdb26e15ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to load millions of data into Mongo DB using Apache Spark 3.0]]></title>
            <link>https://medium.com/@thomaspt748/how-to-load-millions-of-data-into-mongo-db-using-apache-spark-3-0-8bcf089bd6ed?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bcf089bd6ed</guid>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Wed, 11 Dec 2019 00:43:35 GMT</pubDate>
            <atom:updated>2019-12-11T00:45:14.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfWM07MzH4G7eCffAoqCpQ.png" /></figure><p>Mongo DB is a distributed NOSQL(Not Only SQL) database based on a document model where data objects are stored as separate document inside a collection. Each MongoDB instance can have multiple databases and each database can have multiple collections. A document is the basic unit of data for Mongo DB and is nearly equivalent to a row in an RDBMS.</p><p>Let’s see a comparison of Oracle(RDBMS) and Mongo DB(NOSQL).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOv-3Bi28VDpeaan9GP17w.png" /></figure><p>Data in each document is represented as JSON and MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents. The maximum BSON document size is 16 megabytes.</p><p>To get an idea of what a JSON document is, check out the following Figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEr4sQEX9dwIe7p2gwXryw.png" /><figcaption><em>A Mongo document printed as JSON</em></figcaption></figure><p>In this blog we will explore the steps required to load data into Mongo DB database using Apache Spark. In this code example, I’m using H-1B Visa Petitions data(3 million)as my source data which is downloaded from kaggle.com. This example code uses Spark 3.0.0-preview , Scala 2.12.10 and MongoDB 4.2.1.</p><p><strong><em>Step 1: Download dependency jars and add these jars to the Eclipse class path.</em></strong></p><p>a)<a href="https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/3.11.2">mongo-java-driver-3.11.2.jar</a></p><p>b)<a href="https://mvnrepository.com/artifact/org.mongodb/bson/3.11.2">bson-3.11.2.jar</a></p><p>c)<a href="https://mvnrepository.com/artifact/org.mongodb.spark/mongo-spark-connector_2.12/2.4.1">mongo-spark-connector_2.12–2.4.1.jar</a></p><p><strong><em>Step 2: Lets create a scala object named “dataload” and create a SPARK session.</em></strong></p><p>We can set all Input/Output Configuration via the uri setting as seen below. Click <a href="https://docs.mongodb.com/spark-connector/master/configuration/#configure-input-uri">here</a> to see the full list of configuration options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIYB4OxiuJrBB8a5cPMR3g.png" /></figure><p><strong><em>Step 3: Set directory path for the input data file and use Spark DataFrame reader to read the input data(.CSV)file as a Spark DataFrame.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_wlqsXmPwbGktk2CH8dVQ.png" /></figure><p><strong><em>Step 4: Next let’s import the necessary dependencies.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BT_Iaw5vk2NzpgtiF6rywA.png" /></figure><p><strong><em>Step 5: Lets set the database write configurations. “WriteConfig” object can specify various </em></strong><a href="https://docs.mongodb.com/spark-connector/master/configuration/#spark-output-conf"><strong><em>write configuration settings</em></strong></a><strong><em>, such as mongo db collection or the write concern.</em></strong></p><p>In this configuration we are using the Mongo DB collection “employee” and writeConcern.w &quot;majority&quot;.</p><p>“majority” means Write operation returns acknowledgement after propagating to M-number of data-bearing voting members (primary and secondaries)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3c9S1J-TZ8jFfE7QUjXAhg.png" /></figure><p><strong><em>Step 6: Iterate thorough each Spark partition and parse JSON string to Mongo DB Document.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RcLJv1CBPvh-tPxrZqv9Fg.png" /></figure><p><strong><em>Step 7: The following code saves data to the “</em></strong><strong><em>employee&quot; collection with a </em></strong><strong><em>majority </em></strong><a href="https://docs.mongodb.com/manual/reference/write-concern/#write-concern"><strong><em>write concern</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96YCUCe0kY9cuXYC7gMG1Q.png" /></figure><blockquote>Above program took 1 minute 13 secs and 283 milli seconds(1.13.283) to load 3 million records into Mongo DB using the Mongo-Spark-Connector. For the same data set Spark JDBC took 2 minute 22 secs and 194 milli seconds.Based on this it is very clear that Mongo-Spark-Connector Outperform Spark JDBC.</blockquote><p><strong><em>Step 8: Lets retrieve the “employee” collection data using Spark to ensure that data is loaded.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgS6q11R-MpZgk4qpK6MSA.png" /></figure><p>When we execute the above code, the output will be something similar to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuksqS8T0Sbg42pwrb-8lw.png" /></figure><p><strong><em>Final Thoughts…</em></strong></p><p>Mongo DB provides high performance, high availability, and automatic scaling and very easy to implement. With the fast performance of Spark and real-time analytics capabilities of Mongo DB, enterprises can build more robust applications. Moreover Mongo-Spark-Connector gives an edge to MongoDB when working with Spark over other NOSQL databases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bcf089bd6ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Spark Dataframe on HBase table.]]></title>
            <link>https://medium.com/@thomaspt748/how-to-create-spark-dataframe-on-hbase-table-e9c8db31bb30?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c8db31bb30</guid>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hbase]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[spark-streaming]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 03:56:01 GMT</pubDate>
            <atom:updated>2019-12-05T04:17:55.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*tam7_upnC7JLFe-RcWRc4g.png" /></figure><p>Apache HBase and Hive are both data stores for storing unstructured data. HBase is a distributed, scalable, NoSQL big data store that runs on a Hadoop cluster. HBase can host very large tables — billions of rows, millions of columns — and can provide real-time, random read/write access to Hadoop data, whereas Hive is not ideally a database but a map-reduce based SQL engine that runs on top of Hadoop.</p><p>In many of my projects, I had to read HBase data and process and land data into HDFS /DBs. Most easier and common method, many of us adapted to read Hbase is to create a Hive view against the Hbase table and query data using Hive Query Language or read HBase data using Spark-HBase Connector.</p><p>The caveat in using the Hive is every time you run Hive QL, it runs a map-reduce job to retrieve the result set. Better approach is to query data directly from Hbase and compute using Spark. In this blog, let’s explore how to create spark Dataframe from Hbase database table without using Hive view or using Spark-HBase connector. This blog is more code oriented and the explanation are given as code comments…So be ready to get your hands dirty…</p><h4><strong>Step 1. Let’s create the following employee table in HBase Database.</strong></h4><p>Given below is a sample schema of a table named “employee”. It has two column families: “personal” and “professional”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_Ru1HFv50jfTvRK8F0mjQ.png" /></figure><p>You can create this table using HBase shell as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4hOvzE4HKuKik1TBodmbg.png" /></figure><h4><strong>Step 2. Insert Data into employee table</strong></h4><p>You can insert data into HBase table using Java API or HBase Shell.</p><p><strong>2.1. </strong>Insert Data Using HBase Shell<strong>.</strong></p><p><em>Using </em><strong><em>put</em></strong><em> command, you can insert rows into an HBase table.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-f-BegTGYdKQTj-MVoBWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCnCwO1XS5KvWAz2W-imjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wc70xjU3R1GwcHSSxCjOZg.png" /></figure><p><strong>2.2. </strong>Insert Data using Java API and Scala<em>.</em></p><p><em>You can insert data into Hbase using the </em><strong><em>add()</em></strong><em> method of the </em><strong><em>Put</em></strong><em> class. All of these classes belong to the </em><strong><em>org.apache.hadoop.hbase.client</em></strong><em> package. See the scala program below to create data in “employee” Table of HBase.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahwHIkMhSLASXHDIWqeLcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meo2RGHqPmFNTyl1duuMsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Apmgll28s34KTgZq3zU6Q.png" /></figure><h4><strong>Step 3. Let’s check whether records are inserted.</strong></h4><p>Open an HBase shell and type command ‘scan’ as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Us26SD5Zob3bCmdu0nRz8A.png" /></figure><h4><strong>Step 4. Next let’s retrieve the employee table data using Spark DataFrame.</strong></h4><p><em>4.1. Create a spark session with master as “local[*]”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2_YS0UegXGQz0L_tE7cRw.png" /></figure><p><em>4.2. Set HBase configuration parameters using HBaseConfiguration.create() method.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABGTJiRzUHBb5q_dTbXonw.png" /></figure><p><em>4.3. Create HBase connection using ConnectionFactory.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zvcP7AB00fk8BmZPB7xAA.png" /></figure><p><em>4.4. Lets’ create an HBase table instance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1lZ3_-hnltnBr9IHSMT2A.png" /></figure><p><em>4.5. One of the ways to get data from HBase is to scan. Scan allows iteration over multiple rows for specified attributes. Lets’ initiate a client Scan instance and setup a filter criteria to retrieve the rows beginning with “Key”. Next let’s add columns to be included in the result set.The following is an example of a Scan on a Table instance.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zryRwHXA22EKaqDC_Zb38Q.png" /></figure><p><em>4.6. Iterate through each row and fetch data from each cell and store the result set in a List[Map[String,String]] collection.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQv6os3hasw99f175O9ydw.png" /></figure><p><em>4.7. Destroy instances of Scan, Table and Connection to release any resources held..</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4keWgnGEzXWxeCON3ICFlA.png" /></figure><p><em>4.8. Let’s create a Spark DataFrame using the List[Map[String,String]] collection.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-SVPU_WBInJxZnb7Fm1VQ.png" /></figure><p><em>4.9. When you run the above code, </em><strong><em>resultDF.show</em></strong><em> will give the output as displayed below.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-JLE9w64D8khN_sYGonYw.png" /></figure><blockquote><strong>Final Thoughts…</strong></blockquote><p>HBase will be a good candidate If you have hundreds of millions or billions of rows. Traditional RDBMS would be a better choice, If you only have a few thousand/million rows as all of your data might wind up on a single node (or two) and the rest of the cluster may be sitting idle.</p><p>HBase Table instances are not thread-safe. Only one thread can use an instance of Table at any given time. When creating Table instances, it is advisable to use the same HBaseConfiguration instance.Connections are heavyweight objects but thread-safe so you can create one for your application and keep the instance around. Table, Admin and RegionLocator instances are lightweight. Create as you go and then let go as soon as you are done by closing them.</p><p>Happy Coding…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c8db31bb30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to UPSERT data into relational database using Apache Spark: Part 2]]></title>
            <link>https://medium.com/@thomaspt748/how-to-upsert-data-into-relational-database-using-apache-spark-part-2-45a9d49d0f43?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a9d49d0f43</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Sat, 18 May 2019 18:37:33 GMT</pubDate>
            <atom:updated>2022-02-15T03:03:05.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*tTMeZjtTnatp5eln" /></figure><h3>How to UPSERT data into relational database using Apache Spark: Part 2 (Scala Version)</h3><p>In my opinion, Database UPSERT won’t be complete with out talking about MERGE functionality. In this blog we will sail through how we can UPSERT using MERGE command.</p><p>SELECT from a database table and then INSERT or UPDATE based on the condition are the traditional way of handling data UPSERT. With the MERGE statement, you can combine those statements into a single one and improve overall performance of the individual transaction.</p><p>Most of the relational databases support MERGE command. In Part 1 example, I’ve used MySQL. But MERGE is not supported by MySQL, However, there is a different way of achieving the same in MySQL:</p><p><a href="https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html">INSERT…ON DUPLICATE KEY UPDATE</a></p><blockquote>If you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement and the new row causes a duplicate value in the UNIQUE or PRIMARY KEY index, MySQL performs an update to the old row based on the new values.</blockquote><p>In this example I’m going to use DB2 database and MERGE statement. Following is a syntax diagram for the MERGE statement showing all of its principal clauses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*KIwoYnZjQNvs-p75.jpg" /></figure><p>In its simplest form the MERGE statement looks like this:</p><pre>MERGE INTO &lt;table-name&gt;<br>USING &lt;table-reference&gt;<br>AS &lt;correlation-name&gt;<br>ON &lt;search-condition&gt;<br>WHEN NOT MATCHED THEN &lt;insertSQL&gt; THEN <br>WHEN MATCHED THEN &lt;updateSQL&gt;</pre><p>Let’s re-write the <strong>Step 4</strong> in Part 1 example using MERGE command.</p><p><strong>4. Update database table records using Spark.</strong></p><p>For our example let’s say the school city <strong>“Garden City”</strong> is changed to <strong>“NewYork”</strong> and <strong>“University at Albany, State University of New York” is </strong>changed to “<strong>Albany State University”.</strong></p><p>Lets see how this is updated into school table.</p><p>Step 4.1: Get the data from CSV file to update the school table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*C9U4AKq67ZgzkAyOyfCClw.png" /></figure><p>Step 4.2: Setup JDBC connection parameters. Please note that I’ve modified the connection parameter to suite DB2 database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRWMC_mqguls1wxHzBtFtw.png" /></figure><p>Step 4.3: Broadcast JDBC connection parameters to cluster nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*WfXidv3dV8-H7sDYmAEreg.png" /></figure><p>Step 4.4: Browse through each partitioned data and establish the JDBC Connection for each partition and execute the MERGE statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eyMbV0ccxj5cDATvevQZA.png" /></figure><p>In the above example Coalesce is used. You can use repartition also.</p><blockquote>On a side note, here is the difference between coalesce and repartition</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld15_a2h9Ng03hOlkr9H8A.png" /></figure><p>Step 4.5: Execute MERGE statement using the column values and Add the all the dataframe records to a batch and execute the batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LO7mv-x0t11KgK21fMJsA.png" /></figure><p>I have benchmarked both MERGE statement( without optimizing the environment and Query) and SELECT/INSERT/UPDATE statements in a development cluster and MERGE statement took 3 minutes 40 secs to load 100000 records, whereas SELECT/UPDATE/INSERT took 8 minutes 6 seconds. In all my executions MERGE statement performed far superior than the traditional SELECT/and UPDATE/INSERT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a9d49d0f43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upsert data into relational database  using Spark.]]></title>
            <link>https://medium.com/@thomaspt748/how-to-upsert-data-into-relational-database-using-spark-7d2d92e05bb9?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2d92e05bb9</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[upsert]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Fri, 03 May 2019 18:33:40 GMT</pubDate>
            <atom:updated>2022-02-13T05:45:53.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*AtljfmG-FH_mvK9AUN8EhQ.jpeg" /></figure><h3><strong>How to </strong>UPSERT<strong> data into relational database using Apache Spark</strong>: Part 1(Scala Version)</h3><p>Apache Spark has multiple ways to read data from different sources like files, databases etc. But when it comes to loading data into RDBMS(relational database management system), Spark supports only Append and Overlay of the data using dataframes. Spark dataframes do not support Updating of data into a database.</p><p>However I had come across several business use cases where I had to update the data. It was a challenge to handle the scenario when I faced with updating the data using Spark and I thought I will share with you my learning experience and how I solved this issue.</p><p>In this blog we will explore how we can update the RDBMS data using Spark without loosing the power of Spark. I’m using scala language to execute my spark code.Let’s look at an example of reading a sample CSV file with school data and <strong>Upsert</strong> the school data into a school table using Spark data frame.</p><ol><li><strong>Read data from a CSV file</strong></li></ol><p>When we read a <strong>csv</strong> file or text file data using Spark libraries the output value will be an actual spark data frame. Spark parallelize the data and put data into multiple partitions as it reads the data from a file into a data frame. As you know data frame doesn’t contain data until we perform an action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*IBNILFDXFgofU-fUGo53Hg.png" /></figure><p>When we execute the above code, the output will be something similar to below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*SOifWSsOVQNLwRAl3PAM0A.png" /><figcaption>Fig 1. School data from csv file in a Spark Dataframe</figcaption></figure><p><strong>2. Create a database schema and table in MySQL db.</strong>(This step can be skipped if you already have a database table)</p><p>You can use any relational database(that can connect using JDBC) to load data. In this example I’m using MySQL db as target database . And target table name is <strong>school</strong>.</p><p>Step 1: Login to MySQL workbench.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Tn91WXsWo3sZWqGhsgx_dA.png" /></figure><p>Step 2: Create a new schema named <strong>myDB.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*gun2OT5UQDZ17QaSA0T6cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*DJgrlx8Y9rTW0i7GJKUAXQ.png" /></figure><p>myDB schema is created as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*4TlRQ-C86QGuRHlSUC1Q6A.png" /></figure><p>Step 3: Create a new table <strong>School </strong>in myDB schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*FNQS8DqVR70e9f794wyXzw.png" /></figure><p><strong>3. Load spark dataframe data into a database.</strong></p><p>In order to load the data into a database table you need to make sure that the dataframe column names and datatypes match exactly to the column names and datatypes of the target database table. Otherwise it will give an error as below.</p><p>“Exception in thread “main” org.apache.spark.sql.AnalysisException:”</p><p>Now let’s load the above dataframe data(in Fig 1.) into <strong>school</strong> table. See the code snippet below to load the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Hybwe3HJyFqIEKy9913lFg.png" /></figure><p>In the above code <strong>dfCsv.write</strong> function will write the content of the dataframe into a database table using the JDBC connection parameters.</p><p>When writing dataframe data into database spark uses the <strong>SaveMode</strong> to specify the expected behavior of saving a DataFrame to a data source. There are four save modes in Spark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRxOi2rkxxdNsLIaeB0OGw.png" /></figure><p>Okay, Now let’s retrieve the data from the school table to ensure that the data is loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*WbIrzx8PnWcdZtqf6_-h_w.png" /></figure><p>When you run the above code, <strong>schoolDf.show</strong> will give the output as displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*h8RbDEJuMdai24Uu_XLOmA.png" /></figure><p><strong>4. Update database table records using Spark.</strong></p><p>For our example let’s say the school city <strong>“Garden City”</strong> is changed to <strong>“NewYork”</strong> and <strong>“University at Albany, State University of New York” is </strong>changed to “<strong>Albany State University”.</strong></p><p>Lets see how this is updated into school table.</p><p>Step 4.1: Get the data from CSV file to update the school table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*C9U4AKq67ZgzkAyOyfCClw.png" /></figure><p>Step 4.2: Setup JDBC connection parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*8muvS7GIHG89ZJS5iemuIg.png" /></figure><p>Step 4.3: Broadcast JDBC connection parameters to cluster nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*WfXidv3dV8-H7sDYmAEreg.png" /></figure><p>Step 4.4: Browse through each partitioned data and establish the JDBC Connection for each partition and check whether the spark dataframe row exists in the database. If the row exists, generates an UPDATE statement and if row does not exists, creates an INSERT statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*sS5_rbSszYsB_npSLgt_Sg.png" /></figure><p>Step 4.5: Execute a SELECT statement using the key column value to check whether to do an INSERT or UPDATE operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*0_Nd5Htg6POVlkP-duRFBA.png" /></figure><p>Step 4.6: Add the all the dataframe( insert or update) records to a batch and execute the batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4wSCYBlcGzJQMcXVAJMPUQ.png" /></figure><p>If you noticed I have commented commit statement in my code as auto commit was enabled in my case. You need to commit the data at each partition level for you specific use case.</p><p>addBatch and executeBatch should be used only when your columns set in UPDATE/INSERT SQL are same at all the time of execution. If your sql is generated dynamically and the column set are different in each execution, then it is better to use executeUpdate. SELECT,INSERT and UPDATE are the traditional way of handling data UPSERT. Database UPSERT wont be complete with out talking about MERGE functionality. <a href="https://medium.com/@thomaspt748/how-to-upsert-data-into-relational-database-using-apache-spark-part-2-45a9d49d0f43?source=friends_link&amp;sk=1ab271c2e81f7bdf7af06bedaea5cd85">Please continue to read Part 2 for MERGE statement….</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2d92e05bb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most Common Scala Collections used in Spark]]></title>
            <link>https://medium.com/@thomaspt748/most-common-scala-collections-used-in-spark-6031537aa999?source=rss-959b8306437------2</link>
            <guid isPermaLink="false">https://medium.com/p/6031537aa999</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Thomas Thomas]]></dc:creator>
            <pubDate>Tue, 30 Apr 2019 00:44:33 GMT</pubDate>
            <atom:updated>2019-04-30T00:44:33.868Z</atom:updated>
            <content:encoded><![CDATA[<p>The latest Scala release has its new and improved collection library. Scala collection library is very practical and useful.In this blog I will be explaining the scala collections that are widely used in Apache Spark applications.</p><p><strong>Scala collection hierarchy</strong></p><p>The Scala collection classes are part of the <strong>scala.collection</strong> package and its sub- packages. The <strong>scala.collection</strong> provide side-effect operations that could change the state of the collection in place. On the other hand, <strong>scala.collection.immutable</strong> is guaranteed to be immutable for everyone. The immutable collections stays unchanged during the current program execution. Any change in an immutable collection produces a new collection without touching the existing collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*6rQogwH_3tKdTauigWLk1w.png" /><figcaption>Figure 4.1 shows a simplified version of the Scala collection library.</figcaption></figure><p>The root of the hierarchy is the trait Traversable. This base trait implements the behavior common to all collection types in Scala. The only abstract method defined in the Traversable trait is foreach: Scala collections extend from traversable, which is the main trait of all collection’s descends. List structures, for instance, extend from Seq class hierarchy, which means sequence — List is a kind of sequence. All these trees are immutable or mutable depending on the Scala collection package.</p><p><strong>Sequences</strong></p><p>Sequences types let you work with groups of data lined up in order. Because the elements are ordered, you can access the the first element, second element, 100th element, and so on.</p><p><strong>Lists</strong></p><p>In my personal experience the most important sequence type to know about is its class List. Lists support fast addition and removal of items to the beginning of the list, but it does not provide fast access to indexes because the implementation must iterate through the list linearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*VJb-d3AYP-Gc5NECal3QVA.png" /></figure><p><strong>Arrays</strong></p><p>Arrays allow you to hold a sequence of elements and efficiently access an element at an arbitrary position, both to get or update the element, with a zero-based index.</p><p>Here’s how you create an array whose size you know, but don’t know the values of elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*6367qksJBsjY8vZC_janFA.png" /></figure><p>Here’s how you initialize an array when you do know the element values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*glm8hR0dcdRunsTIKvn9MA.png" /></figure><p>As mentioned previously, arrays are accessed in Scala by placing an index in parentheses.</p><p>Here’s an example of both accessing and updating an array element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*pCSyG6gVqt5mwCmCPrnjPw.png" /></figure><p><strong>Map</strong></p><p>A Map is a key/value pair that can be retrieved based on the key, which is unique. Key/value pairs are iterable. However, Map values do not need to be unique.</p><p>Like other Scala collections, you have mutable and immutable Map collections. The key-value pair is represented by <strong>scala.Tuple2</strong>, a tuple of two elements.</p><p>Here’s how you can create an instance of an immutable Map with two key-value pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*nnjhYNDh-XdVGLxe35YcAw.png" /></figure><p>Few more examples of creating a Map and accessing keys and values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*wZPqYKygnUbdMjH1ps29oA.png" /></figure><p>As you can see, Scala uses <strong>scala.collection.immutable.Map </strong>when you create a Map using Map(). Both keys and values are iterable, and you can have access to all the keys with the keys method or to all the values using the values method.</p><p><strong>Set and SortedSet</strong></p><p>Set is an iterable collection type that contains no duplicate elements. Set provides the contains method to check whether the given element exists in the Set, and the apply method that does the same thing.</p><p>Here’s how to use them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*0BroPVrnVaJAYnBlyAjRJQ.png" /></figure><p>Common operation you can perform on Set are add, remove, union, intersect, and diff.</p><p>One interesting subtrait of Set is SortedSet. When iterator or foreach is called on SortedSet, it browse its elements in a certain order.</p><p>In the following code snippet we are adding two sets, one using Set and the other using SortedSet. In the case of SortedSet, the order of the elements is maintained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*wXgXxzXFi2RrgMLHOeXs5Q.png" /></figure><p><strong>Scala tuples</strong></p><p>A scala tuple value is formed by enclosing individual elements in parentheses. Tuples are useful for functions that return more than one values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*idUUs7aBqk2JKxEY2OpdaQ.png" /></figure><p>Scala has special methods called _1 and _2 which you can use to retrieve a tuple’s values. In Tuples, values are kept in order. You need to follow the same order when inserting elements in the tuple.</p><p>Scala recommends to use immutable collections over mutable ones. Scala automatically imports immutable collections, but you have to explicitly import mutable collection types, as you did for collection.mutable.Map.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6031537aa999" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>