<?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 Ganesh on Medium]]></title>
        <description><![CDATA[Stories by Ganesh on Medium]]></description>
        <link>https://medium.com/@ganeshmoorthy.va?source=rss-af1030f3516e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PawD2tR9wJjgfOfZuWB01Q.jpeg</url>
            <title>Stories by Ganesh on Medium</title>
            <link>https://medium.com/@ganeshmoorthy.va?source=rss-af1030f3516e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:41:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ganeshmoorthy.va/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 Spark Manages Executor Memory: Real World Example— Part 2]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/how-spark-manages-executor-memory-real-world-example-part-2-998cb16ce1c0?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/998cb16ce1c0</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 05:36:30 GMT</pubDate>
            <atom:updated>2025-02-03T05:36:30.662Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore how <strong>Spark</strong> manages <strong>Executor Memory</strong> when we configure it, and take a deeper look into the memory allocation and division process. This will help us understand how Spark efficiently utilizes the memory resources provided and how internal configurations affect performance. Please refer <a href="https://medium.com/@ganeshmoorthy.va/how-spark-manages-executor-memory-an-in-depth-look-at-its-architecture-part-1-c54c4fde60c3"><strong><em>part-1</em></strong></a> before diving to this for better understanding</p><p>Let’s assume we are configuring <strong>4GB of executor memory</strong> for each executor using the spark.executor.memory parameter. But here’s the catch: while we request 4GB, <strong>Spark will actually allocate 4.4GB</strong> per executor. Let&#39;s dive into why this happens and how Spark handles memory.</p><h4>Why Spark Allocates More Memory Than Requested</h4><p>When you set spark.executor.memory=4g, Spark doesn’t just allocate the <strong>4GB</strong> for the <strong>JVM heap memory</strong>. Spark internally reserves an additional <strong>10%</strong> of the executor memory for <strong>off-heap memory</strong>.</p><p>So, when we request <strong>4GB</strong>, Spark will reserve:</p><ul><li><strong>4GB</strong> for the JVM heap memory (used for processing tasks, caching data, etc.)</li><li><strong>0.4GB (10% of 4GB)</strong> for <strong>off-heap memory</strong> (used for serialized data, caching, and network buffers)</li></ul><p>Thus, Spark will end up requesting a total of <strong>4.4GB per executor</strong> (4GB + 0.4GB for off-heap memory).</p><h3>Memory Breakdown: What Happens with 4GB of Executor Memory</h3><p>Now that we know Spark is reserving <strong>4.4GB</strong> of memory, let’s break this down further to understand how Spark divides this memory between different components:</p><h4>1. Reserved Memory (300MB)</h4><p>By default, Spark reserves <strong>300MB</strong> of memory for internal overhead tasks. This memory is not used for user computations, data processing, or caching. Instead, it is reserved for:</p><ul><li>Managing internal Spark structures</li><li>Bookkeeping</li><li>Ensuring JVM stability</li></ul><p>This 300MB is <strong>fixed</strong> and does not change with the amount of executor memory allocated, meaning it’s always reserved for internal Spark operations.</p><h4>2. Usable Memory (3700MB)</h4><p>After reserving the <strong>300MB</strong> for internal tasks, Spark is left with the <strong>remaining 3700MB</strong> for actual data processing. This is known as <strong>Usable Memory</strong>.</p><p>The usable memory is where Spark allocates space for:</p><ul><li><strong>Unified Memory</strong> (the dynamic memory pool for both execution and storage)</li><li><strong>User Memory</strong> (for user-defined objects and caching)</li></ul><blockquote><strong>4000MB (requested spark memory) — 300 MB (Reserved)= 3700 MB (Usable memory)</strong></blockquote><h4>3. Unified Memory (2220MB)</h4><p>In Spark, the memory used for both <strong>execution</strong> and <strong>storage</strong> is managed through a mechanism called <strong>Unified Memory</strong>. This means that Spark dynamically shares memory between the two, optimizing memory usage as tasks run. The size of the unified memory is governed by the configuration parameter spark.memory.fraction, which defines the fraction of executor memory allocated for unified memory.</p><p>By default, spark.memory.fraction is set to <strong>0.6</strong>, meaning <strong>60% of the executor memory</strong> is allocated to unified memory.</p><blockquote><strong>60% of 3700 MB (Usable memory) = 2220MB (unified memory)</strong></blockquote><p>In Spark, the <strong>Unified Memory</strong> is divided into two distinct pools:</p><ol><li><strong>Execution Memory</strong>: This pool is used for memory-intensive operations like <strong>shuffling</strong>, <strong>sorting</strong>, <strong>joins</strong>, <strong>aggregations</strong>, and <strong>caching intermediate data</strong> during query execution.</li><li><strong>Storage Memory</strong>: This pool is used for caching RDDs, <strong>DataFrames</strong>, and other objects in memory to avoid re-computation during iterative algorithms or subsequent actions.</li></ol><p>The division between these two pools is controlled by the spark.memory.storageFraction parameter, which defines what fraction of the <strong>Unified Memory</strong> should be allocated to <strong>Storage Memory</strong>. By default, <strong>spark.memory.storageFraction</strong> is set to <strong>0.5</strong>, meaning <strong>50% of the Unified Memory</strong> will be used for <strong>Storage Memory</strong>, while the other 50% will be allocated to <strong>Execution Memory</strong>.</p><blockquote><strong>1110MB (Storage Memory) + 1110MB (Execution Memory) = 2220MB (unified memory)x</strong></blockquote><h4>4. User Memory (1480MB)</h4><p>It’s important to keep in mind that <strong>User Memory</strong> is not reserved strictly for user data. It’s part of the <strong>usable memory</strong>, so if Spark runs out of space in <strong>Unified Memory</strong> (Execution or Storage Memory), it can start using <strong>User Memory</strong> as well, which could lead to spilling data to disk.</p><p>For example:</p><ul><li>If we perform a lot of <strong>shuffling</strong>, <strong>sorting</strong>, or <strong>joining</strong>, Spark will consume more <strong>Execution Memory</strong>, which can result in spilling to <strong>User Memory</strong> if the unified memory is exhausted.</li><li>If we cache large datasets, this will consume more <strong>Storage Memory</strong> and, potentially, spill into <strong>User Memory</strong> if needed.</li></ul><blockquote><strong>40% of 3700 MB (Usable memory) = 1480 MB (User memory)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2TX7O4Smzk2_-EOk4PmIA.jpeg" /></figure><p>That’s all for now !! If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998cb16ce1c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spark’s Handling of File Reads: RDD vs DataFrame]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/understanding-sparks-handling-of-file-reads-rdd-vs-dataframe-25e9f436e72e?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e9f436e72e</guid>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 07:03:15 GMT</pubDate>
            <atom:updated>2025-01-06T07:03:15.965Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll explore how Spark treats reading from a file using two different APIs: the lower-level <strong>RDD API</strong> and the higher-level <strong>DataFrame API</strong>. Before diving into specific examples, let’s first understand a few key terminologies in Spark that will help us clarify how jobs are triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yGj5FFIlKA8iaD_ForK57w.jpeg" /></figure><h3>Jobs in Spark</h3><p>In Spark, a <strong>job</strong> is only created when an <strong>action</strong> is executed, not when a <strong>transformation</strong> (such as map, filter, or select) is applied. This distinction is important because Spark uses <strong>lazy evaluation</strong> for transformations, meaning it doesn&#39;t execute them immediately. Instead, it builds a computation plan or a Directed Acyclic Graph (DAG) of stages and tasks.</p><p>A <strong>job</strong> in Spark is triggered only when one of the following <strong>actions</strong> is executed:</p><ul><li>collect()</li><li>count()</li><li>save()</li><li>take()</li><li>reduce()</li><li>first()</li><li>foreach()</li><li>show() (for DataFrame/Dataset API)</li></ul><p>These actions instruct Spark to actually perform the computation and return a result, either locally or distributed across the cluster. It’s worth noting that actions lead to the execution of the plan and the creation of a job, while transformations only define the DAG without triggering any computation.</p><h4>Reading File — RDD</h4><p>Let’s start by reading a CSV file using the <strong>RDD</strong> API in Spark, but without triggering any actions. Since actions are required to create a job in Spark, we will refrain from calling any action in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1da80f6ce1f4a4556376a0867b8883b5/href">https://medium.com/media/1da80f6ce1f4a4556376a0867b8883b5/href</a></iframe><p>Since we haven’t invoked any <strong>actions</strong> (like collect(), count(), or save()), Spark won’t create a job. The transformation textFile() is <strong>lazy</strong>, meaning it only defines the data source and transformation plan, but does not trigger any computation.</p><blockquote><strong>What Happens Behind the Scenes?</strong></blockquote><ul><li><strong>No Job is Created</strong>: As there is no action to trigger execution, Spark won’t create a job. You won’t see any job listed in the Spark UI.</li><li><strong>Lazy Evaluation</strong>: The RDD transformation (textFile()) only builds the computation plan but doesn’t execute it.</li></ul><p>In the <strong>Spark UI</strong>, you will not see any active jobs, stages, or tasks since no computation has been triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVuwWeNCUAtwrS227NH3ow.png" /><figcaption><strong>RDD read csv without Action</strong></figcaption></figure><blockquote><em>Even if you provide a non-existing file path, Spark will </em><strong><em>not throw an error</em></strong><em> immediately when you call a transformation like </em><em>sc.textFile(&quot;path/to/non_existing_file.csv&quot;)<br></em>Spark won’t throw errors for missing files until an <strong>action</strong> is executed</blockquote><h4>Reading File — DataFrame</h4><p>Let’s now try reading the same CSV file using the <strong>DataFrame API</strong> in Spark. Although reading a file is typically considered a <strong>transformation</strong>, <strong>a job will still be triggered</strong> when using the DataFrame API. This behaviour differs from RDDs, where transformations like map or filter do not trigger a job until an action is called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d9c33208916a6fbae67da4d176b13a3/href">https://medium.com/media/5d9c33208916a6fbae67da4d176b13a3/href</a></iframe><h3>Why Does a Job Get Triggered?</h3><p>In the <strong>DataFrame API</strong>, even though reading from a file like spark.read.csv() is technically a <strong>transformation</strong>, Spark implicitly triggers a job immediately. Here’s why:</p><ul><li><strong>Implicit Job Trigger</strong>: The DataFrame read operation involves more complex logic, such as inferring the schema, checking the file, and setting up data partitions. Spark performs this processing as part of the job execution.</li><li><strong>Inferred Schema and Data Loading</strong>: As soon as you call spark.read.csv(), Spark attempts to read the file and infer its schema, which kicks off the job behind the scenes. In the case of Parquet (and other columnar formats), Spark needs to read the file’s metadata to determine the schema. This step requires Spark to start the job in the background to load and organize the data.</li></ul><p>Even though reading the file is considered a transformation step, Spark does not wait for an explicit action to start executing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cj3iWhzdLyvn5YEJ7xarg.png" /><figcaption><strong>DataFrame read csv without Action</strong></figcaption></figure><h3>Summary:</h3><ul><li><strong>RDD</strong>: <em>Jobs are triggered only when an </em><strong><em>action</em></strong><em> is executed</em>. Transformations like reading a file (sc.textFile()) are lazy and do not create a job until computation is required.</li><li><strong>DataFrame</strong>: <em>Reading files with DataFrame</em> APIs (e.g., spark.read.csv()) <em>automatically triggers a job</em>, even though reading is a transformation. This happens because Spark needs to optimize the data loading process (schema inference, partitioning).</li></ul><p>That’s all for now !! If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e9f436e72e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding Data Corruption: The Risks of Reading and Writing to the Same Path in PySpark]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/avoiding-data-corruption-the-risks-of-reading-and-writing-to-the-same-path-in-pyspark-90e21c6ca724?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/90e21c6ca724</guid>
            <category><![CDATA[write]]></category>
            <category><![CDATA[failure]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 14:20:08 GMT</pubDate>
            <atom:updated>2024-10-12T14:20:08.507Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore how Spark behaves when reading from and writing to the same location. Before diving into that, let’s first understand the different write modes available in Spark for saving a DataFrame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*6QzYZ3JJnfWmp4JARC72RA.jpeg" /></figure><ol><li><em>append</em>: Append contents of the DataFrame to existing data.</li><li><em>overwrite</em>: Overwrite existing data.</li><li><em>error or errorifexistes</em>: Throw an exception if data already exists.</li><li><em>ignore</em>: Silently ignore this operation if data already exists.</li></ol><p>For our experiment we will focus exclusively on the append and overwrite mode. In this example, we are going to consider sample <a href="https://drive.google.com/uc?id=1OT84-j5J5z2tHoUvikJtoJFInWmlyYzY&amp;export=download">customers-1000.csv</a> files with 1000 records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_D1aG7rL4YYE2CyjpHZ4g.png" /><figcaption>Local File Tree Location</figcaption></figure><blockquote><strong>Reading CSV file</strong></blockquote><p>We will read a CSV file in PySpark and load it into a DataFrame. After that, we will perform some transformations, such as:</p><ul><li><strong>Dropping unwanted columns</strong></li><li><strong>Concatenating two columns</strong> (for the sake of demonstrating transformations)</li></ul><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import *<br><br>spark = SparkSession.builder.appName(&quot;UnionTest&quot;).getOrCreate()<br>df = spark.read.format(&quot;csv&quot;) \<br>        .option(&quot;path&quot;, &quot;union_input&quot;) \<br>        .option(&quot;header&quot;, &quot;true&quot;)\<br>        .option(&quot;inferSchema&quot;, &quot;true&quot;)\<br>        .load()<br><br>df = df.drop(&quot;Index&quot;)<br>df = df.withColumn(&quot;Phone&quot;, concat(col(&quot;Phone 1&quot;), col(&quot;Phone 2&quot;)))<br>df = df.drop(&quot;Phone 1&quot;).drop(&quot;Phone 2&quot;)<br>df.show(5)<br>df.printSchema()</pre><pre><br>+---------------+----------+---------+--------------------+----------------+----------------+--------------------+-----------------+--------------------+--------------------+<br>|    Customer Id|First Name|Last Name|             Company|            City|         Country|               Email|Subscription Date|             Website|               Phone|<br>+---------------+----------+---------+--------------------+----------------+----------------+--------------------+-----------------+--------------------+--------------------+<br>|dE014d010c7ab0c|    Andrew|  Goodman|       Stewart-Flynn|     Rowlandberg|           Macao|marieyates@gomez-...|       2021-07-26|http://www.shea.biz/|846-790-4623x4715...|<br>|2B54172c8b65eC3|     Alvin|     Lane|Terry, Proctor an...|        Bethside|Papua New Guinea|alexandra86@mccoy...|       2021-06-24|http://www.pena-c...|124-597-8652x0568...|<br>|d794Dd48988d2ac|     Jenna|  Harding|        Bailey Group|    Moniquemouth|           China|justincurtis@pier...|       2020-04-05|http://www.booth-...|(335)987-3085x378...|<br>|3b3Aa4aCc68f3Be|  Fernando|     Ford|        Moss-Maxwell|      Leeborough|           Macao| adeleon@hubbard.org|       2020-11-29|http://www.hebert...|(047)752-3122048....|<br>|D60df62ad2ae41E|      Kara|    Woods|     Mccarthy-Kelley|Port Jacksonland|           Nepal|jesus90@roberson....|       2022-04-22| http://merritt.com/|+1-360-693-4419x1...|<br>+---------------+----------+---------+--------------------+----------------+----------------+--------------------+-----------------+--------------------+--------------------+<br>only showing top 5 rows<br><br>root<br>|-- Customer Id: string (nullable = true)<br>|-- First Name: string (nullable = true)<br>|-- Last Name: string (nullable = true)<br>|-- Company: string (nullable = true)<br>|-- City: string (nullable = true)<br>|-- Country: string (nullable = true)<br>|-- Email: string (nullable = true)<br>|-- Subscription Date: date (nullable = true)<br>|-- Website: string (nullable = true)<br>|-- Phone: string (nullable = true)</pre><blockquote><strong>Writing CSV file in Append Mode</strong></blockquote><p>We will attempt to load our transformed DataFrame back to the same location from which we read the data, and then analyze the results.</p><pre>df.coalesce(1).write.mode(&quot;append&quot;).format(&quot;csv&quot;)\<br>    .option(&quot;header&quot;, &quot;true&quot;)\<br>    .option(&quot;path&quot;, &quot;union_input&quot;)\<br>    .save()</pre><p>The operation was successful; it did not modify our actual input file but created new files in the same location without any errors. Below, I am attaching a screenshot of the input file tree, where the files created during this operation are highlighted in yellow for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ICh-3sNCsBtq50NCiLmig.png" /><figcaption>Local File Tree Location After performing Append Operation</figcaption></figure><blockquote><strong>Writing CSV file in Overwrite Mode</strong></blockquote><p>We will clear our input location and perform the same operation using <strong>overwrite</strong> mode, after which we will analyze the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_D1aG7rL4YYE2CyjpHZ4g.png" /><figcaption>Local File Tree Location Before performing Overwrite Operation</figcaption></figure><pre>df.coalesce(1).write.mode(&quot;overwrite&quot;).format(&quot;csv&quot;)\<br>    .option(&quot;header&quot;, &quot;true&quot;)\<br>    .option(&quot;path&quot;, &quot;union_input&quot;)\<br>    .save()</pre><p>However, this <strong><em>operation failed with a “file not found” error</em></strong>, despite the input file being present during execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3wHY86qhvEowZifLpoEbA.png" /><figcaption>Input File Not Found</figcaption></figure><blockquote><strong>Why writing to same reading path failed in Overwrite Mode ?</strong></blockquote><ul><li><strong>Execution Plan Behaviour</strong>: In overwrite mode, Spark’s execution plan includes a step to delete the existing files at the target path before writing new data. If a read operation is still in progress, Spark may attempt to access files that have already been deleted, resulting in a “file not found” error.</li><li><strong>Lazy Evaluation</strong>: Spark employs lazy evaluation, meaning that transformations are not executed until an action is triggered. When the write action is called, Spark constructs a Directed Acyclic Graph (DAG) that includes all transformations. If part of this DAG attempts to read from a location that is being deleted, it leads to inconsistencies.</li><li><strong>Concurrent Operations</strong>: If the read operation is concurrent with the delete action initiated by the overwrite operation, the read may end up accessing an empty or nonexistent directory, leading to errors.</li><li><strong>File System Behaviour</strong>: Some file systems may not handle concurrent read and write operations smoothly, further complicating the situation.</li></ul><blockquote><strong>Workarounds</strong></blockquote><h4>Cache:</h4><p>If we know that the DataFrame size is small enough to fit into memory, we can cache the transformed DataFrame before performing the write operation. However, this method is not recommended due to potential risks associated with memory management and performance.</p><pre>df.cache()<br>df.coalesce(1).write.mode(&quot;overwrite&quot;).format(&quot;csv&quot;)\<br>    .option(&quot;header&quot;, &quot;true&quot;)\<br>    .option(&quot;path&quot;, &quot;/Users/ganeshmoorthy/Desktop/coding/medium/union_input&quot;)\<br>    .save()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cR455B3R3fsyUuwranX75Q.png" /><figcaption>Local File Tree Location After Cache and Overwrite Operation</figcaption></figure><h4>Temporary Location:</h4><p>We can first write to a temporary location and then use those files as the source for writing to our destination location. This approach is one of the best ways to avoid job failures.</p><h3>Illustrative Code Snippet</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50b8a8f4c7238ced9b267e461083f93b/href">https://medium.com/media/50b8a8f4c7238ced9b267e461083f93b/href</a></iframe><p>That’s all for now !! If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90e21c6ca724" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spark Manages Executor Memory: An In-Depth Look at Its Architecture — Part 1]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/how-spark-manages-executor-memory-an-in-depth-look-at-its-architecture-part-1-c54c4fde60c3?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c54c4fde60c3</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 20:09:27 GMT</pubDate>
            <atom:updated>2024-09-04T20:09:27.073Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Spark Manages Executor Memory: An In-Depth Look at Its Architecture — Part 1</h3><p>Apache Spark is renowned for its in-memory processing capabilities, which significantly speed up data processing tasks by minimising disk I/O. Efficient memory management within Spark executors is essential for maximizing performance and avoiding common pitfalls such as out-of-memory errors or excessive garbage collection.</p><h3>Spark’s Memory Architecture</h3><p>In Spark, memory management is divided into several components:</p><ol><li><strong>Driver Memory</strong>: Manages the SparkSession/SparkContext and coordinates job execution.</li><li><strong>Executor Memory</strong>: Handles the execution of tasks and storage of data. This is where most of the memory management intricacies occur.</li></ol><p>Driver’s memory management is relatively simple; Spark does not make specific plans. So, in this article lets deep dive into Executor memory.</p><h3>Executor memory</h3><p>The executor acts as a JVM process launched on a worker node. The JVM has two types of memory,</p><ol><li>On-Heap Memory</li><li>Off-Heap Memory</li></ol><p>In addition to the above two JVM memory types, there is one more segment of memory that is accessed by Spark, i.e., external process memory. This kind of memory is mainly used for PySpark and SparkR applications. This is the memory used by the Python/R process, which resides outside the JVM.</p><h4>On-Heap Memory</h4><p>Spark uses on-heap memory only. The size of the on-heap memory is configured by the--executor-memory or spark.executor.memoryparameter when the Spark application starts. The concurrent tasks running inside Executor share the JVM’s on-heap memory.</p><p>Apache Spark supports three memory regions:</p><ul><li>Reserved Memory</li><li>User Memory</li><li>Spark Memory or Spark Unified Memory</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*L2SA-QhRswikJ5DZrUjpZw.png" /><figcaption>Spark Memory Regions</figcaption></figure><h4><strong>Reserved Memory</strong></h4><p>Reserved memory is used to store Spark’s internal objects, including:</p><ul><li><strong>Task Metadata</strong>: Information about the tasks being executed.</li><li><strong>Shuffle Data</strong>: Temporary data related to shuffle operations.</li><li><strong>Other Internal Structures</strong>: Various internal objects and structures required by Spark.</li></ul><p><strong><em>Reserved memory’s size is hard coded</em></strong>, and its size cannot be changed in any way without Spark recompilation or setting <em>spark.testing.reserved</em> Memory, which is not recommended as it is a testing parameter not intended to be used in production.</p><blockquote>RESERVED_SYSTEM_MEMORY_BYTES : 300 MB (Cannot be changed)</blockquote><p>Whenever we allocate spark.executor.memory , we cannot utilise the complete memory instead the usable memory becomes spark.executor.memory — 300MB</p><blockquote>Usable Memory = Allocated JVM Heap Memory {spark.executor.memory} — Reserved Memory{300Mb}</blockquote><h4>Spark Memory or Spark Unified Memory</h4><p>Spark Memory is the memory pool managed by Apache Spark. Spark Memory is responsible for storing intermediate states while doing task execution like joins or storing broadcast variables. All the cached or persistent data will be stored in this segment, specifically in the storage memory of this segment.</p><p>Spark memory is controlled by spark.memory.fraction and fraction of the heap space used for execution and storage. The lower this is, the more frequently spills and cached data eviction occur. The purpose of this config is to set aside memory for internal metadata, user data structures, and imprecise size estimation in the case of sparse, unusually large records. Leaving this at the default value is recommended.</p><blockquote>spark.memory.fraction : 0.6 (Default Value)</blockquote><blockquote>Spark Memory = Usable Memory * spark.memory.fraction{0.6}</blockquote><p>Spark tasks operate in two main memory regions:</p><ul><li><strong>Execution Memory:</strong> Used for shuffles, joins, sorts, and aggregations.</li><li><strong>Storage Memory:</strong> used to cache partitions of data.</li></ul><p>The boundary between them is set by,</p><blockquote><em>spark.memory.storageFraction</em>: 0.5 (Default Value)</blockquote><h4>Storage Memory</h4><p>Storage Memory is used for storing all of the cached data, broadcast variables, unrolled data, etc. “Unroll” is essentially a process of deserializing serialized data.</p><p>Any persistent option that includes memory in it will store that data in this segment.</p><p><em>Spark clears space</em> for new cache requests by removing old cached objects based on the <strong><em>Least Recently Used (LRU) </em></strong>mechanism.</p><p>Once the cached data is out of storage, it is either written to disk or recomputed based on configuration. Broadcast variables are stored in the cache at the MEMORY_AND_DISK persistent level. This is where we store cached data, which is long-lived.</p><blockquote>Storage Memory = Spark Memory * spark.memory.storageFraction{0.5}</blockquote><h4>Execution Memory</h4><p>Used for performing computations such as shuffles, joins, and aggregations. It handles memory required for task execution.</p><p>For example, it is used to store the shuffle intermediate buffer on the map side in memory. Also, it is used to store a hash table for the hash aggregation step.</p><p>This pool also supports spilling on disk if not enough memory is available, but the blocks from this pool cannot be forcefully evicted by other threads (tasks).</p><p>Execution memory tends to be more short-lived than storage. It is evicted immediately after each operation, making space for the next ones.</p><blockquote>Execution Memory = Spark Memory * (1 — spark.memory.storageFraction{0.5})</blockquote><p>Storage and execution pool borrowing rules:</p><ol><li>Storage memory can borrow space from execution memory only if blocks are not used in execution memory.</li><li>Execution memory can also borrow space from storage memory if blocks are not used in storage memory.</li><li>If blocks from Execution memory is used by Storage memory and Execution needs more memory, it can <em>forcefully evict the excess blocks occupied by Storage Memory</em></li><li>If blocks from storage memory are used by execution memory and storage needs more memory, it <em>cannot forcefully evict the excess blocks occupied by execution memory</em>; it will have less memory area. It will wait until Spark releases the excess blocks stored in execution memory and then occupies them.</li></ol><h4>User Memory</h4><p>User Memory includes:</p><ul><li><strong>User-Defined Data Structures</strong>: Memory used by custom data structures created by users, such as hash tables, maps, or other objects needed for complex operations.</li><li><strong>Spark Internal Metadata</strong>: Metadata related to user-defined operations, including RDD (Resilient Distributed Dataset) dependencies and information needed for data processing.</li><li><strong>User-Defined Functions (UDFs)</strong>: Memory consumed by UDFs created by users, which are functions applied to data during transformations and actions.</li><li><strong>RDD Conversion Data</strong>: Memory used for storing information related to RDD conversions and dependencies.</li></ul><blockquote>User Memory = Usable Memory * (1 — spark.memory.fraction{0.6})</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*dUwAPlI1f2eyXpBQOjIQ1g.jpeg" /><figcaption>Spark On Heap Memory</figcaption></figure><h3>Off-Heap Memory</h3><p>Although most of the operations in Spark happens inside the JVM and subsequently uses the JVM Heap for its memory, each executor has the ability to utilize an off-heap space for certain cases. This off-heap space lies outside the JVM space and is generally accessed via sun.misc.Unsafe APIs. The off-heap memory is outside the ambit of Garbage Collection, hence it provides more fine-grained control over the memory for the application developer.</p><p>Spark uses off-heap memory for two purposes:</p><ul><li>A part of off-heap memory is used by Java internally for purposes like String interning and JVM overheads.</li><li>Off-Heap memory can also be used by Spark explicitly for storing its data as part of <a href="https://issues.apache.org/jira/browse/SPARK-7075">Project Tungsten</a> <a href="https://medium.com/walmartglobaltech/decoding-memory-in-spark-parameters-that-are-often-confused-c11be7488a24#f407">[5]</a>.</li></ul><p>The total off-heap memory for a Spark executor is controlled by spark.executor.memoryOverhead.</p><blockquote>Off Heap Memory = Max (10% of spark.executor.memory , 300 MB) <strong>(Cannot be changed)</strong></blockquote><p>This means, even if the user does not explicitly set this parameter, Spark would set aside 10% of executor memory(or 384MB whichever is higher) for VM overheads. If we set <em>spark.executor.memory=1Gb </em>then spark application will request 1GB + 384MB from yarn node manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKtK-R_grWL5YNP9ARyqwQ.png" /><figcaption>Spark Memory Allocation for On Heap and Off Heap</figcaption></figure><h3>Stay Tuned for Example Explanation!</h3><p>In Part 2 of this series, we’ll dive into practical examples and real-world implementations of the concepts discussed here. Don’t miss out on how these ideas come to life in actual scenarios!</p><p>If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c54c4fde60c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2— Unlocking Potential: The Ultimate Guide to Catalyst Optimization]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/part-2-unlocking-potential-the-ultimate-guide-to-catalyst-optimization-a0cd965cd734?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0cd965cd734</guid>
            <category><![CDATA[optimization-techniques]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[catalyst-optimizer]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 16:29:16 GMT</pubDate>
            <atom:updated>2024-08-13T16:29:16.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl4TEDealaPAP6ig_a2y4w.jpeg" /></figure><p>In our <a href="https://medium.com/@ganeshmoorthy.va/part-1-unlocking-potential-the-ultimate-guide-to-catalyst-optimization-d32852458ca1">previous article</a>, we explored the theoretical aspects of Spark’s Catalyst optimizer. Today, we’ll dive into practical examples to see how Catalyst works in action. We’ll use a sample <a href="https://github.com/Teradata/kylo/blob/master/samples/sample-data/parquet/userdata1.parquet">user</a> dataset to illustrate various optimization techniques applied by Catalyst. By the end of this article, you’ll have a clear understanding of how Spark optimizes queries and improves performance.</p><h4>Setting Up Environment</h4><p>Before we start analyzing, let’s set up our Spark environment and create a DataFrame from our sample data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4485914dcc95fa10f57cefdf118693a6/href">https://medium.com/media/4485914dcc95fa10f57cefdf118693a6/href</a></iframe><blockquote><strong>Output</strong></blockquote><pre>+-------------------+---+----------+---------+------------------------+------+---------------+-------------------+----------------------+----------+---------+----------------------------+----------------------------+<br>|registration_dttm  |id |first_name|last_name|email                   |gender|ip_address     |cc                 |country               |birthdate |salary   |title                       |comments                    |<br>+-------------------+---+----------+---------+------------------------+------+---------------+-------------------+----------------------+----------+---------+----------------------------+----------------------------+<br>|2016-02-03 13:25:29|1  |Amanda    |Jordan   |ajordan0@com.com        |Female|1.197.201.2    |6759521864920116   |Indonesia             |3/8/1971  |49756.53 |Internal Auditor            |1E+02                       |<br>|2016-02-03 22:34:03|2  |Albert    |Freeman  |afreeman1@is.gd         |Male  |218.111.175.34 |                   |Canada                |1/16/1968 |150280.17|Accountant IV               |                            |<br>|2016-02-03 06:39:31|3  |Evelyn    |Morgan   |emorgan2@altervista.org |Female|7.161.136.94   |6767119071901597   |Russia                |2/1/1960  |144972.51|Structural Engineer         |                            |<br>|2016-02-03 06:06:21|4  |Denise    |Riley    |driley3@gmpg.org        |Female|140.35.109.83  |3576031598965625   |China                 |4/8/1997  |90263.05 |Senior Cost Accountant      |                            |<br>|2016-02-03 10:35:31|5  |Carlos    |Burns    |cburns4@miitbeian.gov.cn|      |169.113.235.40 |5602256255204850   |South Africa          |          |NULL     |                            |                            |<br>|2016-02-03 12:52:34|6  |Kathryn   |White    |kwhite5@google.com      |Female|195.131.81.179 |3583136326049310   |Indonesia             |2/25/1983 |69227.11 |Account Executive           |                            |<br>|2016-02-03 14:03:08|7  |Samuel    |Holmes   |sholmes6@foxnews.com    |Male  |232.234.81.197 |3582641366974690   |Portugal              |12/18/1987|14247.62 |Senior Financial Analyst    |                            |<br>|2016-02-03 12:17:06|8  |Harry     |Howell   |hhowell7@eepurl.com     |Male  |91.235.51.73   |                   |Bosnia and Herzegovina|3/1/1962  |186469.43|Web Developer IV            |                            |<br>|2016-02-03 09:22:53|9  |Jose      |Foster   |jfoster8@yelp.com       |Male  |132.31.53.61   |                   |South Korea           |3/27/1992 |231067.84|Software Test Engineer I    |1E+02                       |<br>|2016-02-03 23:59:47|10 |Emily     |Stewart  |estewart9@opensource.org|Female|143.28.251.245 |3574254110301671   |Nigeria               |1/28/1997 |27234.28 |Health Coach IV             |                            |<br>|2016-02-03 05:40:42|11 |Susan     |Perkins  |sperkinsa@patch.com     |Female|180.85.0.62    |3573823609854134   |Russia                |          |210001.95|                            |                            |<br>|2016-02-03 23:34:34|12 |Alice     |Berry    |aberryb@wikipedia.org   |Female|246.225.12.189 |4917830851454417   |China                 |8/12/1968 |22944.53 |Quality Engineer            |                            |<br>|2016-02-04 00:18:17|13 |Justin    |Berry    |jberryc@usatoday.com    |Male  |157.7.146.43   |6331109912871813274|Zambia                |8/15/1975 |44165.46 |Structural Analysis Engineer|                            |<br>|2016-02-04 03:16:52|14 |Kathy     |Reynolds |kreynoldsd@redcross.org |Female|81.254.172.13  |5537178462965976   |Bosnia and Herzegovina|6/27/1970 |286592.99|Librarian                   |                            |<br>|2016-02-03 14:23:23|15 |Dorothy   |Hudson   |dhudsone@blogger.com    |Female|8.59.7.0       |3542586858224170   |Japan                 |12/20/1989|157099.71|Nurse Practicioner          |&lt;script&gt;alert(&#39;hi&#39;)&lt;/script&gt;|<br>|2016-02-03 06:14:01|16 |Bruce     |Willis   |bwillisf@bluehost.com   |Male  |239.182.219.189|3573030625927601   |Brazil                |          |239100.65|                            |                            |<br>|2016-02-03 06:27:45|17 |Emily     |Andrews  |eandrewsg@cornell.edu   |Female|29.231.180.172 |30271790537626     |Russia                |4/13/1990 |116800.65|Food Chemist                |                            |<br>|2016-02-03 22:14:24|18 |Stephen   |Wallace  |swallaceh@netvibes.com  |Male  |152.49.213.62  |5433943468526428   |Ukraine               |1/15/1978 |248877.99|Account Representative I    |                            |<br>|2016-02-03 17:15:54|19 |Clarence  |Lawson   |clawsoni@vkontakte.ru   |Male  |107.175.15.152 |3544052814080964   |Russia                |          |177122.99|                            |                            |<br>|2016-02-03 16:00:36|20 |Rebecca   |Bell     |rbellj@bandcamp.com     |Female|172.215.104.127|                   |China                 |          |137251.19|                            |                            |<br>+-------------------+---+----------+---------+------------------------+------+---------------+-------------------+----------------------+----------+---------+----------------------------+----------------------------+<br>only showing top 20 rows<br><br>root<br> |-- registration_dttm: timestamp (nullable = true)<br> |-- id: integer (nullable = true)<br> |-- first_name: string (nullable = true)<br> |-- last_name: string (nullable = true)<br> |-- email: string (nullable = true)<br> |-- gender: string (nullable = true)<br> |-- ip_address: string (nullable = true)<br> |-- cc: string (nullable = true)<br> |-- country: string (nullable = true)<br> |-- birthdate: string (nullable = true)<br> |-- salary: double (nullable = true)<br> |-- title: string (nullable = true)<br> |-- comments: string (nullable = true)</pre><h4>Null Propagation:</h4><p>In Spark’s Catalyst optimizer null propagation refers to the optimization techniques and rules applied to handle and propagate null values efficiently within query execution. Lets see few examples for this,</p><blockquote><strong>Example-1</strong></blockquote><p>In our DataFrame, where the salary column contains null values, the Catalyst optimizer in Spark automatically rewrites the query during the filter operation. This optimization is applied in the <strong><em>Optimized Logical Plan</em></strong> to efficiently handle null values, enhancing query performance.</p><pre>val null_query_rewrite = df.filter(col(&quot;salary&quot;) === 90263.05)<br>null_query_rewrite.show(false)<br>null_query_rewrite.explain(true)</pre><p><em>Parsed Logical Plan &amp; Analyzed Logical Plan</em> → ‘Filter (‘salary = 90263.05)</p><p><em>Optimized Logical Plan</em> → Filter (<strong><em>isnotnull(salary#10)</em></strong> AND (salary#10 = 90263.05))</p><p>In the Optimized Logical Plan, the Catalyst optimizer rewrites the query to efficiently handle null values. It adds a condition to check that salary is not null before applying the equality filter. This optimization helps in avoiding unnecessary computations and improves query performance.</p><pre>== Parsed Logical Plan ==<br>&#39;Filter (&#39;salary = 90263.05)<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Analyzed Logical Plan ==<br>registration_dttm: timestamp, id: int, first_name: string, last_name: string, email: string, gender: string, ip_address: string, cc: string, country: string, birthdate: string, salary: double, title: string, comments: string<br>Filter (salary#10 = 90263.05)<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Optimized Logical Plan ==<br>Filter (isnotnull(salary#10) AND (salary#10 = 90263.05))<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Physical Plan ==<br>*(1) Filter (isnotnull(salary#10) AND (salary#10 = 90263.05))<br>+- *(1) ColumnarToRow<br>   +- FileScan parquet [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] Batched: true, DataFilters: [isnotnull(salary#10), (salary#10 = 90263.05)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/ganeshmoorthy/Desktop/coding/medium/input/userdata1.parquet], PartitionFilters: [], PushedFilters: [IsNotNull(salary), EqualTo(salary,90263.05)], ReadSchema: struct&lt;registration_dttm:timestamp,id:int,first_name:string,last_name:string,email:string,gender:...</pre><blockquote><strong>Example-2</strong></blockquote><p>When you perform an operation like adding 10 to the salary column, where some values might be null, the optimizer ensures that the result is handled correctly (NULL + 10 = NULL).</p><pre>val null_propagation_rules = df.withColumn(&quot;new_salary&quot;, col(&quot;salary&quot;)+10 )<br>null_propagation_rules.select(&quot;salary&quot;, &quot;new_salary&quot;).show(false)<br>null_propagation_rules.explain(true)</pre><pre>+---------+----------+<br>|salary   |new_salary|<br>+---------+----------+<br>|49756.53 |49766.53  |<br>|150280.17|150290.17 |<br>|144972.51|144982.51 |<br>|90263.05 |90273.05  |<br>|NULL     |NULL      |<br>|137251.19|137261.19 |<br>+---------+----------+<br><br>== Parsed Logical Plan ==<br>&#39;Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, (&#39;salary + 10) AS new_salary#26]<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Analyzed Logical Plan ==<br>registration_dttm: timestamp, id: int, first_name: string, last_name: string, email: string, gender: string, ip_address: string, cc: string, country: string, birthdate: string, salary: double, title: string, comments: string, new_salary: double<br>Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, (salary#10 + cast(10 as double)) AS new_salary#26]<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Optimized Logical Plan ==<br>Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, (salary#10 + 10.0) AS new_salary#26]<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Physical Plan ==<br>*(1) Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, (salary#10 + 10.0) AS new_salary#26]<br>+- *(1) ColumnarToRow<br>   +- FileScan parquet [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] Batched: true, DataFilters: [], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/ganeshmoorthy/Desktop/coding/medium/input/userdata1.parquet], PartitionFilters: [], PushedFilters: [], ReadSchema: struct&lt;registration_dttm:timestamp,id:int,first_name:string,last_name:string,email:string,gender:...</pre><h4>Predicate Pushdown:</h4><p>Predicate pushdown is a technique where filters are pushed down into the query plan to reduce the amount of data processed.</p><blockquote><strong>Example-3</strong></blockquote><p>Consider a DataFrame where we first concatenate first_name and last_name columns and then filter the rows based on the salary column. The code might look something like this:</p><pre>val concat_names = df.withColumn(&quot;full_name&quot;, concat(col(&quot;first_name&quot;),col(&quot;last_name&quot;)))<br>val predicate_push_down_df = concat_names.filter(col(&quot;salary&quot;) === 90263.05)<br>predicate_push_down_df.explain(true)</pre><p>Due to predicate pushdown, Spark’s Catalyst optimizer will adjust the query execution plan to enhance performance. Instead of performing the concatenation first and then filtering, the optimizer will push the filter condition down to reduce the size of the DataFrame before applying the concatenation logic.</p><pre>== Parsed Logical Plan ==<br>&#39;Filter (&#39;salary = 90263.05)<br>+- Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, concat(first_name#2, last_name#3) AS full_name#26]<br>   +- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Analyzed Logical Plan ==<br>registration_dttm: timestamp, id: int, first_name: string, last_name: string, email: string, gender: string, ip_address: string, cc: string, country: string, birthdate: string, salary: double, title: string, comments: string, full_name: string<br>Filter (salary#10 = 90263.05)<br>+- Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, concat(first_name#2, last_name#3) AS full_name#26]<br>   +- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Optimized Logical Plan ==<br>Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, concat(first_name#2, last_name#3) AS full_name#26]<br>+- Filter (isnotnull(salary#10) AND (salary#10 = 90263.05))<br>   +- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Physical Plan ==<br>*(1) Project [registration_dttm#0, id#1, first_name#2, last_name#3, email#4, gender#5, ip_address#6, cc#7, country#8, birthdate#9, salary#10, title#11, comments#12, concat(first_name#2, last_name#3) AS full_name#26]<br>+- *(1) Filter (isnotnull(salary#10) AND (salary#10 = 90263.05))<br>   +- *(1) ColumnarToRow<br>      +- FileScan parquet [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] Batched: true, DataFilters: [isnotnull(salary#10), (salary#10 = 90263.05)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/ganeshmoorthy/Desktop/coding/medium/input/userdata1.parquet], PartitionFilters: [], PushedFilters: [IsNotNull(salary), EqualTo(salary,90263.05)], ReadSchema: struct&lt;registration_dttm:timestamp,id:int,first_name:string,last_name:string,email:string,gender:...</pre><h4>Constant Folding:</h4><p>Constant folding involves simplifying expressions with constant values. If an expression only involves constants, Spark will compute its result beforehand, reducing the computational workload during query execution</p><h4>Projection Pruning:</h4><p>Projection pruning is an optimization technique where only the necessary columns are selected, reducing the amount of data shuffled and processed.</p><blockquote><strong>Example-4</strong></blockquote><p>Let’s consider an example where we add two constant values, 50 and 70, and use the result to create a new column named total.</p><pre>val constant_folding = df.select(col(&quot;id&quot;), lit(50) + lit(70) as &quot;total&quot;)<br>constant_folding.explain(true)</pre><ul><li><strong>Constant Folding</strong>: The optimizer computes 50 + 70 during the optimization phase, resulting in 120.</li><li><strong>Efficiency</strong>: The computed constant value 120 is then applied to the total column for every row, improving performance by avoiding redundant calculations.</li><li>We are selecting only id and total column from our dataframe, due to <strong>Projection Pruning</strong> spark will read only id column from the source and ignores all other columns. This pruning is <em>applied during the Physical Plan stage of query optimization</em>, ensuring that only relevant data is handled.</li></ul><pre>== Parsed Logical Plan ==<br>&#39;Project [&#39;id, (50 + 70) AS total#26]<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Analyzed Logical Plan ==<br>id: int, total: int<br>Project [id#1, (50 + 70) AS total#26]<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Optimized Logical Plan ==<br>Project [id#1, 120 AS total#26]<br>+- Relation [registration_dttm#0,id#1,first_name#2,last_name#3,email#4,gender#5,ip_address#6,cc#7,country#8,birthdate#9,salary#10,title#11,comments#12] parquet<br><br>== Physical Plan ==<br>*(1) Project [id#1, 120 AS total#26]<br>+- *(1) ColumnarToRow<br>   +- FileScan parquet [id#1] Batched: true, DataFilters: [], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/ganeshmoorthy/Desktop/coding/medium/input/userdata1.parquet], PartitionFilters: [], PushedFilters: [], ReadSchema: struct&lt;id:int&gt;</pre><p><strong><em>Source Code:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a88b221cd8a6c4760b813632afd391/href">https://medium.com/media/40a88b221cd8a6c4760b813632afd391/href</a></iframe><p>That’s all for now. If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0cd965cd734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1 — Unlocking Potential: The Ultimate Guide to Catalyst Optimization]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/part-1-unlocking-potential-the-ultimate-guide-to-catalyst-optimization-d32852458ca1?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d32852458ca1</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[catalyst-optimizer]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 19:02:30 GMT</pubDate>
            <atom:updated>2024-08-04T19:02:30.875Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1 — Unlocking Potential: The Ultimate Guide to Catalyst Optimization</h3><p>Catalyst Optimizer is the core of Spark SQL, which leverages advanced programming language features (e.g. Scala’s <a href="https://docs.scala-lang.org/tour/pattern-matching.html">pattern matching</a> and <a href="https://docs.scala-lang.org/overviews/quasiquotes/intro.html">quasiquotes</a>) in a novel way to build an extensible query optimizer. Catalyst is based on functional programming constructs in Scala and designed with these key two purposes:</p><ul><li>Easily add new optimization techniques and features to Spark SQL</li><li>Enable external developers to extend the optimizer (e.g. adding data source specific rules, support for new data types, etc.)</li></ul><p>The <strong><em>main data type in Catalyst is a tree</em> </strong>composed of node objects. Each node has a node type and zero or more children. At its core, Catalyst contains a general library for representing trees and applying rules to manipulate them. On top of this framework, databricks have built libraries specific to relational query processing (e.g., expressions, logical query plans), and several sets of rules that handle different phases of query execution: <strong><em>analysis, logical optimization, physical planning, and code generation</em></strong> to compile parts of queries to Java bytecode. Databricks used another Scala feature, <a href="https://docs.scala-lang.org/overviews/quasiquotes/intro.html">quasiquotes</a>, that makes it easy to generate code at runtime from composable expressions. Finally, Catalyst offers several public extension points, including external data sources and user-defined types.</p><h4>Query Execution Process</h4><p>Catalyst’s general tree transformation framework is used in four phases, as shown below: (1) analyzing a logical plan to resolve references, (2) logical plan optimization, (3) physical planning, and (4) code generation to compile parts of the query to Java bytecode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wcB65zspdLOFh0crk748g.png" /><figcaption>Catalyst Optimizer</figcaption></figure><h3>Analysis Phase</h3><blockquote><strong>Unresolved Logical Plan</strong></blockquote><ol><li>When a SQL query is submitted to Spark, it is first parsed into an <strong>unresolved logical plan</strong>.</li><li>This plan represents the structure of the query but contains references to table names, columns, and functions that are not yet fully resolved.</li><li>This serves as an intermediate representation of the query. It allows Spark to perform initial checks and transformations before resolving all references and validating the query.</li></ol><blockquote><strong>Logical Plan</strong></blockquote><p>Spark SQL uses Catalyst rules and a Catalog object that tracks the tables in all data sources to resolve attributes. <strong><em>Analysis phase </em></strong>starts by building an <em>Unresolved Logical Plan</em> tree with unbound attributes and data types, then applies below rules to generate the <em>Logical Plan</em>:</p><ul><li>Looking up relations by name from the catalog.</li><li>Mapping named attributes, such as col, to the input provided given operator’s children.</li><li>Determining which attributes refer to the same value to give them a unique ID (which later allows optimization of expressions such as col = col).</li><li>Propagating and coercing types through expressions: for example, we cannot know the return type of 1 + col until we have resolved col and possibly casted its subexpressions to a compatible types.</li></ul><h3>Logical Optimization Phase</h3><blockquote><strong>Optimized Logical Plan</strong></blockquote><p>The <strong><em>logical optimization phase</em> </strong>applies standard rule-based optimizations to the logical plan. These include,</p><ol><li><em>Constant Folding</em>: If an expression only involves constants, Spark will compute its result beforehand, reducing the computational workload during query execution</li><li><em>Predicate Pushdown</em>: Pushing the filter condition closer to source</li><li><em>Projection Pruning</em>:<em> </em>Selecting only required or used columns in the query</li><li><em>Null Propagation</em>: Handling the null aware operations in query</li><li><em>Boolean expression simplification</em>, and other rules.</li></ol><h3>Physical Planning phase</h3><blockquote><strong>Physical Plans</strong></blockquote><p><strong><em>Physical Planning phase</em></strong> takes an optimized logical plan and generates one or more physical plans, using physical operators that match the Spark execution engine. It then selects a plan using a cost model. At the moment, cost-based optimization is only used to select join algorithms: for relations that are known to be small, Spark SQL uses a broadcast join, using a peer-to-peer broadcast facility available in Spark.</p><p>The physical planner also performs rule-based physical optimizations, such as pipelining projections or filters into one Spark map operation. In addition, it can push operations from the logical plan into data sources that support predicate or projection pushdown.</p><h3>Code Generation</h3><p>The final phase of query optimization involves generating Java bytecode to run on each machine.</p><h3>Stay Tuned for Part 2!</h3><p>In Part 2 of this series, we’ll dive into practical examples and real-world implementations of the concepts discussed here. Don’t miss out on how these ideas come to life in actual scenarios!</p><p>If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><p><em>Resources:</em></p><p><a href="https://people.csail.mit.edu/matei/papers/2015/sigmod_spark_sql.pdf">https://people.csail.mit.edu/matei/papers/2015/sigmod_spark_sql.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d32852458ca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark’s Structured API: Maximizing Efficiency with Column String, Object, and Expression…]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/apache-sparks-structured-api-maximizing-efficiency-with-column-string-object-and-expression-c85f023fd9f4?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85f023fd9f4</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 06:11:37 GMT</pubDate>
            <atom:updated>2024-07-27T06:13:13.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Spark’s Structured API: Maximizing Efficiency with Column String, Object, and Expression Access</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*AaNd4aYGYLOckKJMJQ6wmg.png" /></figure><p>In this article, we will understand various methods of accessing columns within a DataFrame in Apache Spark. Efficient column access is crucial for data manipulation and analysis tasks. Here, we explore three primary methods:</p><ol><li>Column String</li><li>Column Object</li><li>Column Expression</li></ol><p>Lets take an example from our <a href="https://medium.com/@ganeshmoorthy.va/demystifying-complex-datatypes-how-to-attach-schemas-for-arrays-json-and-nested-json-in-spark-54538796e556">previous blog</a> of loading CSV to a dataFrame as df. Find the output of dataFrame and its Schema below,</p><blockquote><strong>df.show(false)</strong></blockquote><pre>+---------+------------------+----------+---------+--------+----------------------------------------------------------+<br>|Username |Email             |Identifier|Firstname|Lastname|Favourites                                                |<br>+---------+------------------+----------+---------+--------+----------------------------------------------------------+<br>|booker12 |rachel@example.com|9012      |Rachel   |Booker  |{[Red, Blue], {[Noodles, Chilli Chickem], [Pizza, Pasta]}}|<br>|grey07   |NULL              |2070      |Laura    |Grey    |{[Yellow, Green], {[Noodles, Lamb], [Pizza]}}             |<br>|johnson81|NULL              |4081      |Craig    |Johnson |{[Violet, Blue], {[Chicken, Noodles], [Pizza, Pasta]}}    |<br>|jenkins46|mary@example.com  |9346      |Mary     |Jenkins |{[Red, Pink], {[Noodles], [Pizza]}}                       |<br>|smith79  |jamie@example.com |5079      |Jamie    |Smith   |{[Purple, Pink], {[Chicken, Fried Rice], [Pasta]}}        |<br>+---------+------------------+----------+---------+--------+----------------------------------------------------------+</pre><blockquote><strong>df.printSchema()</strong></blockquote><pre>root<br> |-- Username: string (nullable = true)<br> |-- Email: string (nullable = true)<br> |-- Identifier: integer (nullable = true)<br> |-- Firstname: string (nullable = true)<br> |-- Lastname: string (nullable = true)<br> |-- Favourites: struct (nullable = true)<br> |    |-- color: array (nullable = true)<br> |    |    |-- element: string (containsNull = true)<br> |    |-- food: struct (nullable = true)<br> |    |    |-- chinese: array (nullable = true)<br> |    |    |    |-- element: string (containsNull = true)<br> |    |    |-- Italian: array (nullable = true)<br> |    |    |    |-- element: string (containsNull = true)</pre><h3><strong>Column String</strong></h3><p>One of the simplest ways to access a column in a DataFrame is by referencing its name as a string. This method is straightforward and intuitive, making it ideal for quick data retrieval tasks.</p><pre>// Select Firstname, Lastname and Favourite Colour using column String<br>df.select(&quot;Username&quot;, &quot;Identifier&quot;, &quot;Favourites.color&quot;, &quot;Favourites.food.chinese&quot;).show(false)</pre><h3>Column Object</h3><p>A Column object in Apache Spark represents a column in a DataFrame. It encapsulates various operations and transformations that can be performed on the data within that column. Column objects are typically created using functions from org.apache.spark.sql.functions, such as col, expr, lit, etc. This approach provides more flexibility and allows for advanced operations such as aliasing, aggregation, and more complex transformations. In Column object we can use below notations,</p><blockquote>col(“columnName”), column(“columnName”), $“columnName”, ‘columnName</blockquote><pre>import spark.implicits._<br>import org.apache.spark.sql.functions._<br>// Select Firstname, Lastname and Favourite Colour using column String<br>df.select(col(&quot;Firstname&quot;), &#39;Lastname, $&quot;Favourites.color&quot;, column(&quot;Favourites.food.chinese&quot;)).show(false)</pre><blockquote>Output for both Column String and Column Object</blockquote><pre>+---------+--------+---------------+-------------------------+<br>|Firstname|Lastname|color          |chinese                  |<br>+---------+--------+---------------+-------------------------+<br>|Rachel   |Booker  |[Red, Blue]    |[Noodles, Chilli Chickem]|<br>|Laura    |Grey    |[Yellow, Green]|[Noodles, Lamb]          |<br>|Craig    |Johnson |[Violet, Blue] |[Chicken, Noodles]       |<br>|Mary     |Jenkins |[Red, Pink]    |[Noodles]                |<br>|Jamie    |Smith   |[Purple, Pink] |[Chicken, Fried Rice]    |<br>+---------+--------+---------------+-------------------------+</pre><h3>Column Expressions</h3><p>Column expressions enable powerful transformations by combining multiple columns or applying built-in functions. They are instrumental in creating new columns or performing calculations across existing ones. When we use a column expression, Spark internally creates a Column object representing that expression for execution. So, <strong><em>combining column object and column expression works seamlessly</em></strong>.</p><pre>//  column expression<br>df.select($&quot;Firstname&quot;, &#39;Lastname, concat(col(&quot;Firstname&quot;), lit(&quot; &quot;), col(&quot;Lastname&quot;))).show(false)</pre><blockquote>Output</blockquote><pre>+---------+--------+------------------------------+<br>|Firstname|Lastname|concat(Firstname,  , Lastname)|<br>+---------+--------+------------------------------+<br>|Rachel   |Booker  |Rachel Booker                 |<br>|Laura    |Grey    |Laura Grey                    |<br>|Craig    |Johnson |Craig Johnson                 |<br>|Mary     |Jenkins |Mary Jenkins                  |<br>|Jamie    |Smith   |Jamie Smith                   |<br>+---------+--------+------------------------------+</pre><h3>Failure Scenarios</h3><blockquote>Can we combine Column String with Column Object ?</blockquote><pre>//  combining column string and column object<br>df.select(col(&quot;Firstname&quot;), &quot;Lastname&quot;).show(false)</pre><p>Spark expects either column object or column string <strong><em>we can’t combine both</em></strong>. In Spark, the select method expects either column objects or column strings, but not a combination of both. This limitation arises because Spark provides two distinct select methods:</p><ol><li><strong>One method</strong> takes column strings as arguments: select(col: String, cols: String*).</li><li><strong>The other method</strong> accepts column objects as arguments: select(cols: org.apache.spark.sql.Column*).</li></ol><p>Since these methods are defined to handle different types of arguments, Spark cannot automatically determine which method to use if both column strings and column objects are passed simultaneously. Consequently, this ambiguity leads to the following error:</p><pre>overloaded method value select with alternatives:<br>  [U1, U2](c1: org.apache.spark.sql.TypedColumn[org.apache.spark.sql.Row,U1], c2: org.apache.spark.sql.TypedColumn[org.apache.spark.sql.Row,U2])org.apache.spark.sql.Dataset[(U1, U2)]<br>  &lt;and&gt;<br>  (col: String,cols: String*)org.apache.spark.sql.DataFrame<br>  &lt;and&gt;<br>  (cols: org.apache.spark.sql.Column*)org.apache.spark.sql.DataFrame<br> cannot be applied to (org.apache.spark.sql.Column, String)</pre><blockquote>Using $ and ‘ notations can we access all column types ?</blockquote><p>First lets try using $ notation to access struct columns in dataFrame</p><pre>//  checking $ notation for accessing json column<br>df.select($&quot;Favourites.color&quot;).show(false)<br><br>+---------------+<br>|color          |<br>+---------------+<br>|[Red, Blue]    |<br>|[Yellow, Green]|<br>|[Violet, Blue] |<br>|[Red, Pink]    |<br>|[Purple, Pink] |<br>+---------------+</pre><p>But, when we try with <strong>‘ </strong>notation, we would get exception. <strong><em>We can’t use ‘ for accessing struct columns.</em></strong></p><pre>//  checking &#39; notation for accessing json column<br>df.select(&#39;Favourites.food.chinese).show(false)<br><br>Exception:<br>value food is not a member of Symbol<br>  df.select(&#39;Favourites.food.chinese).show(false)</pre><blockquote>Can we combine Column Strings and Column Expression ?</blockquote><pre>//combine column string with column expression<br>df.select(&quot;Firstname&quot;, &quot;concat(Firstname, &#39; &#39;, Lastname)&quot;).show(false)<br><br>Exception:<br>Exception in thread &quot;main&quot; org.apache.spark.sql.AnalysisException: <br>[UNRESOLVED_COLUMN.WITH_SUGGESTION]<br>A column or function parameter with name `concat(Firstname, &#39; &#39;, Lastname)` cannot be resolved.</pre><p><em>We can not combine them directly instead we can use </em><em>expr</em></p><p>Either we need to use expr for the expression and convert other columns to column object.</p><pre>//  combine column expression with column object<br>df.select(col(&quot;Firstname&quot;), expr(&quot;concat(Firstname, &#39; &#39;, Lastname)&quot;)).show(false)</pre><p>Or we can use selectExpr and use the column string notations.</p><pre>//combine column string with column expression<br>df.selectExpr(&quot;Firstname&quot;, &quot;concat(Firstname, &#39; &#39;, Lastname)&quot;).show(false)</pre><blockquote>Output</blockquote><pre>+---------+------------------------------+<br>|Firstname|concat(Firstname,  , Lastname)|<br>+---------+------------------------------+<br>|Rachel   |Rachel Booker                 |<br>|Laura    |Laura Grey                    |<br>|Craig    |Craig Johnson                 |<br>|Mary     |Mary Jenkins                  |<br>|Jamie    |Jamie Smith                   |<br>+---------+------------------------------+</pre><h4>Illustrative Code Snippet</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cde698b2b6080947e04e497baa3c1fe9/href">https://medium.com/media/cde698b2b6080947e04e497baa3c1fe9/href</a></iframe><p>That’s all for now !! If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85f023fd9f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Complex Datatypes: How to attach Schemas for Arrays, Json and Nested Json in Spark…]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/demystifying-complex-datatypes-how-to-attach-schemas-for-arrays-json-and-nested-json-in-spark-54538796e556?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/54538796e556</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[nested-json]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 16:06:16 GMT</pubDate>
            <atom:updated>2024-07-14T16:08:19.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying Complex Datatypes: How to attach Schemas for Arrays, Json and Nested Json in Spark DataFrames</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*CpyQl3ic-mqfdOz8hFgd-w.jpeg" /></figure><p>In this article, let’s delve into how we can attach schemas specifically to CSV files. While schemas are inherently attached to file formats like Parquet, Avro, and ORC within their metadata or file headers, our focus here is on CSV files. This is because CSV files do not store schema information alongside the data, unlike Parquet, Avro, and ORC formats. Therefore, when working with CSV files in Apache Spark, schema definition becomes crucial for accurately interpreting and processing the data.</p><p>However, it’s important to note that despite schemas being attached to Parquet, Avro, and ORC files by default, Spark provides the flexibility to override these schemas. This capability allows us to explicitly define schemas for any file format within Spark, ensuring that data is interpreted correctly and aligns with specific data processing requirements.</p><p>By exploring how to attach schemas to CSV files in Spark, we can understand the process of defining and applying schemas more comprehensively. This empowers us to handle diverse data formats effectively, enabling seamless integration and manipulation of data across different storage formats within Apache Spark.</p><p>Let us consider the below <strong><em>“inputs/user_details.csv”</em></strong> file with delimiter “;” as a source for this article,</p><pre>Username;Email;Identifier;Firstname;Lastname;Favourites<br>booker12;rachel@example.com;9012;Rachel;Booker;{&quot;color&quot;:[&quot;Red&quot;,&quot;Blue&quot;],&quot;food&quot;:{&quot;chinese&quot;:[&quot;Noodles&quot;, &quot;Chilli Chickem&quot;],&quot;Italian&quot;:[&quot;Pizza&quot;,&quot;Pasta&quot;]}}<br>grey07;;2070;Laura;Grey;{&quot;color&quot;:[&quot;Yellow&quot;,&quot;Green&quot;],&quot;food&quot;:{&quot;chinese&quot;:[&quot;Noodles&quot;, &quot;Lamb&quot;],&quot;Italian&quot;:[&quot;Pizza&quot;]}}<br>johnson81;;4081;Craig;Johnson;{&quot;color&quot;:[&quot;Violet&quot;,&quot;Blue&quot;],&quot;food&quot;:{&quot;chinese&quot;:[&quot;Chicken&quot;, &quot;Noodles&quot;],&quot;Italian&quot;:[&quot;Pizza&quot;,&quot;Pasta&quot;]}}<br>jenkins46;mary@example.com;9346;Mary;Jenkins;{&quot;color&quot;:[&quot;Red&quot;,&quot;Pink&quot;],&quot;food&quot;:{&quot;chinese&quot;:[&quot;Noodles&quot;],&quot;Italian&quot;:[&quot;Pizza&quot;]}}<br>smith79;jamie@example.com;5079;Jamie;Smith;{&quot;color&quot;:[&quot;Purple&quot;,&quot;Pink&quot;],&quot;food&quot;:{&quot;chinese&quot;:[&quot;Chicken&quot;, &quot;Fried Rice&quot;],&quot;Italian&quot;:[&quot;Pasta&quot;]}}</pre><p>Even though CSV doesn’t store schema, Spark allows us to infer the schema while reading by passing the option(“inferSchema”, “true”). However, this comes with the following disadvantages:</p><ol><li>This involves reading a portion of the data to analyze its structure and infer the data types of each column before applying further transformations or actions.</li><li>This operation incurs additional overhead in terms of I/O operations and processing time, especially for large datasets or when dealing with complex data formats.</li><li>Therefore, <strong><em>schema inference introduces an additional stage in the Spark job execution plan</em></strong> for performing the above activity.</li><li>It may lead to unexpected schema errors if the inferred schema does not match the actual data structure.</li><li>In production environments, where performance and predictability are crucial, it’s advisable to explicitly define schemas to avoid the overhead of schema inference.</li></ol><p>Let’s utilize the following boilerplate code to read a CSV file and experiment with multiple schemas to gain a better understanding of them,</p><pre>import org.apache.spark.SparkConf<br>import org.apache.spark.sql.SparkSession<br>import org.apache.spark.sql.types._<br><br>object column_access extends App{<br>  val sparkConfig = new SparkConf()<br>  sparkConfig.set(&quot;spark.app.name&quot;, &quot;columnAccess&quot;)<br>  sparkConfig.set(&quot;spark.master&quot;, &quot;local[*]&quot;)<br>  val spark = SparkSession.builder().config(sparkConfig).getOrCreate()<br>  val schema = StructType(<br>    List(<br>      StructField(&quot;Username&quot;, StringType, nullable = false),<br>      StructField(&quot;Email&quot;, StringType),<br>      StructField(&quot;Identifier&quot;, IntegerType, nullable = false),<br>      StructField(&quot;Firstname&quot;, StringType),<br>      StructField(&quot;Lastname&quot;, StringType),<br>      StructField(&quot;Favourites&quot;, StringType)<br>    )<br>  )<br>  val inputDf = spark.read.format(&quot;csv&quot;)<br>    .option(&quot;path&quot;, &quot;inputs/user_details.csv&quot;)<br>    .option(&quot;header&quot;, &quot;true&quot;)<br>    .schema(schema)<br>    .option(&quot;delimiter&quot;, &quot;;&quot;)<br>    .load()<br>  inputDf.show()<br>  inputDf.printSchema()<br></pre><blockquote><strong>OUTPUT</strong></blockquote><pre>+---------+------------------+----------+---------+--------+--------------------+<br>| Username|             Email|Identifier|Firstname|Lastname|          Favourites|<br>+---------+------------------+----------+---------+--------+--------------------+<br>| booker12|rachel@example.com|      9012|   Rachel|  Booker|{&quot;color&quot;:[&quot;Red&quot;,&quot;...|<br>|   grey07|              NULL|      2070|    Laura|    Grey|{&quot;color&quot;:[&quot;Yellow...|<br>|johnson81|              NULL|      4081|    Craig| Johnson|{&quot;color&quot;:[&quot;Violet...|<br>|jenkins46|  mary@example.com|      9346|     Mary| Jenkins|{&quot;color&quot;:[&quot;Red&quot;,&quot;...|<br>|  smith79| jamie@example.com|      5079|    Jamie|   Smith|{&quot;color&quot;:[&quot;Purple...|<br>+---------+------------------+----------+---------+--------+--------------------+<br><br>root<br> |-- Username: string (nullable = true)<br> |-- Email: string (nullable = true)<br> |-- Identifier: integer (nullable = true)<br> |-- Firstname: string (nullable = true)<br> |-- Lastname: string (nullable = true)<br> |-- Favourites: string (nullable = true)</pre><p><strong><em>Even though we know “Favourites” column is of JSON/STRUCT type, why have we used as string ?</em></strong></p><p>In Apache Spark, when dealing with data in CSV format that includes fields serialized as JSON, attaching a JSON schema directly to the JSON field within the CSV file isn’t typically supported.</p><p><strong><em>How to attach schema for JSON column in spark ?</em></strong></p><p>Initially read the JSON column as StringType and then use Spark’s from_json function to parse this JSON string into a structured format based on a defined JSON schema. Below is the Json schema for our Favourites column,</p><pre>val foodSchema = StructType(List(<br>    StructField(&quot;chinese&quot;, ArrayType(StringType)),<br>    StructField(&quot;Italian&quot;, ArrayType(StringType))<br>  ))<br><br>val favouritesSchema = StructType(List(<br>  StructField(&quot;color&quot;, ArrayType(StringType)),<br>  StructField(&quot;food&quot;, foodSchema),<br>))<br>// inputDf is from the above code, here we are just attaching schema for Json column<br>val df = inputDf.withColumn(&quot;Favourites&quot;, from_json(col(&quot;Favourites&quot;), favouritesSchema))<br>df.printSchema()</pre><blockquote><strong>Output</strong></blockquote><pre>root<br> |-- Username: string (nullable = true)<br> |-- Email: string (nullable = true)<br> |-- Identifier: integer (nullable = true)<br> |-- Firstname: string (nullable = true)<br> |-- Lastname: string (nullable = true)<br> |-- Favourites: struct (nullable = true)<br> |    |-- color: array (nullable = true)<br> |    |    |-- element: string (containsNull = true)<br> |    |-- food: struct (nullable = true)<br> |    |    |-- chinese: array (nullable = true)<br> |    |    |    |-- element: string (containsNull = true)<br> |    |    |-- Italian: array (nullable = true)<br> |    |    |    |-- element: string (containsNull = true)</pre><h4>Reviewing several findings below</h4><p><strong><em>Nullable Field:</em></strong></p><p>When defining the schema for a DataFrame in Spark, such as for the Username column with nullable = false, it&#39;s important to note that the schema printing (df.printSchema()) displays nullable = true. This discrepancy arises because Spark&#39;s schema printing reflects the actual observed nullability in the data during schema inference and loading.</p><p>If <em>Spark encounters null values or infers potential nullability based on the data content</em>, it may override the specified nullable property in the schema. Therefore, while you&#39;ve explicitly set nullable = false to enforce non-nullability for certain columns, Spark&#39;s schema printing reflects the practical handling of null values during data processing.</p><p><strong><em>What happens when we try to attach JSON schema directly?</em></strong></p><p>If we try to specify a JSON schema directly within a CSV file, Spark throws an error indicating that the data format or type is unsupported.</p><blockquote>org.apache.spark.sql.AnalysisException [UNSUPPORTED_DATA_TYPE_FOR_DATASOURCE]</blockquote><pre>val schema = StructType(<br>    List(<br>      StructField(&quot;Username&quot;, StringType, nullable = false),<br>      StructField(&quot;Email&quot;, StringType),<br>      StructField(&quot;Identifier&quot;, IntegerType, nullable = false),<br>      StructField(&quot;Firstname&quot;, StringType),<br>      StructField(&quot;Lastname&quot;, StringType),<br>      // here we have used the Json schema which we defined above for from_json parser<br>      StructField(&quot;Favourites&quot;, favouritesSchema)<br>    )<br>  )</pre><pre>Exception in thread &quot;main&quot; org.apache.spark.sql.AnalysisException: [UNSUPPORTED_DATA_TYPE_FOR_DATASOURCE] <br>The CSV datasource doesn&#39;t support the column `Favourites` of the type &quot;STRUCT&lt;color: ARRAY&lt;STRING&gt;, food: STRUCT&lt;chinese: ARRAY&lt;STRING&gt;, Italian: ARRAY&lt;STRING&gt;&gt;&gt;&quot;.</pre><p><strong><em>Use Miss-matching schema:</em></strong></p><p>We will try giving IntergerType for Username column and check what happens,</p><pre>val schema = StructType(<br>    List(<br>      StructField(&quot;Username&quot;, IntegerType, nullable = false),<br>      StructField(&quot;Email&quot;, StringType),<br>      StructField(&quot;Identifier&quot;, IntegerType, nullable = false),<br>      StructField(&quot;Firstname&quot;, StringType),<br>      StructField(&quot;Lastname&quot;, StringType),<br>      StructField(&quot;Favourites&quot;, StringType)<br>    )<br>  )<br>val inputDf = spark.read.format(&quot;csv&quot;)<br>    .option(&quot;path&quot;, &quot;inputs/user_details.csv&quot;)<br>    .option(&quot;header&quot;, &quot;true&quot;)<br>    .schema(schema)<br>    .option(&quot;delimiter&quot;, &quot;;&quot;)<br>    .load()<br>inputDf.show()<br>inputDf.printSchema()</pre><p>If we use above schema and try printing the inputDf, <strong><em>we don’t get any exception instead we will have NULL</em></strong> values in Username column. Refer below output,</p><pre>+--------+------------------+----------+---------+--------+--------------------+<br>|Username|             Email|Identifier|Firstname|Lastname|          Favourites|<br>+--------+------------------+----------+---------+--------+--------------------+<br>|    NULL|rachel@example.com|      9012|   Rachel|  Booker|{&quot;color&quot;:[&quot;Red&quot;,&quot;...|<br>|    NULL|              NULL|      2070|    Laura|    Grey|{&quot;color&quot;:[&quot;Yellow...|<br>|    NULL|              NULL|      4081|    Craig| Johnson|{&quot;color&quot;:[&quot;Violet...|<br>|    NULL|  mary@example.com|      9346|     Mary| Jenkins|{&quot;color&quot;:[&quot;Red&quot;,&quot;...|<br>|    NULL| jamie@example.com|      5079|    Jamie|   Smith|{&quot;color&quot;:[&quot;Purple...|<br>+--------+------------------+----------+---------+--------+--------------------+<br><br>root<br> |-- Username: integer (nullable = true)<br> |-- Email: string (nullable = true)<br> |-- Identifier: integer (nullable = true)<br> |-- Firstname: string (nullable = true)<br> |-- Lastname: string (nullable = true)<br> |-- Favourites: string (nullable = true)</pre><p><strong><em>Why spark doesn’t fail for Miss-matching schema?</em></strong></p><p>To handle schema mismatches when reading CSV files in Spark, we can utilize the mode option with PERMISSIVE, or FAILFAST to specify how Spark should handle mismatches or missing columns.</p><p>PERMISSIVE: when it meets a corrupted record, sets malformed fields to null. Default mode is PERMISSIVE thats the reason, we don’t get any exception instead only Username field is marked as NULL</p><p>FAILFAST: throws an exception when it meets corrupted records.</p><p>Lets quickly checkout the results for FAILFAST for the same mis-match schema we have defined above,</p><pre>  val inputDf = spark.read.format(&quot;csv&quot;)<br>    .option(&quot;path&quot;, &quot;inputs/user_details.csv&quot;)<br>    .option(&quot;header&quot;, &quot;true&quot;)<br>    .schema(schema)<br>    .option(&quot;enforceSchema&quot;, &quot;true&quot;)<br>    .option(&quot;mode&quot;, &quot;FAILFAST&quot;)<br>    .option(&quot;delimiter&quot;, &quot;;&quot;)<br>    .load()</pre><blockquote>OUTPUT</blockquote><pre>EXCEPTION:<br>Caused by: org.apache.spark.SparkException: <br>[MALFORMED_RECORD_IN_PARSING.WITHOUT_SUGGESTION] Malformed records are detected in record parsing: [null,rachel@example.com,9012,Rachel,Booker,{&quot;color&quot;:[&quot;Red&quot;,&quot;Blue&quot;],&quot;food&quot;:{&quot;chinese&quot;:[&quot;Noodles&quot;, &quot;Chilli Chickem&quot;],&quot;Italian&quot;:[&quot;Pizza&quot;,&quot;Pasta&quot;]}}].<br>Parse Mode: FAILFAST. To process malformed records as null result, try setting the option &#39;mode&#39; as &#39;PERMISSIVE&#39;.</pre><p>That’s all for now. Stay tuned for various methods to access these columns in our upcoming article.</p><p>If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54538796e556" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Execution Differences: Filter Transformation in RDD vs DataFrame]]></title>
            <link>https://medium.com/@ganeshmoorthy.va/understanding-execution-differences-filter-transformation-in-rdd-vs-sparks-structured-api-7539d72d5469?source=rss-af1030f3516e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7539d72d5469</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Ganesh]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 14:49:50 GMT</pubDate>
            <atom:updated>2024-07-15T04:47:17.095Z</atom:updated>
            <content:encoded><![CDATA[<p>In Apache Spark, the execution order of transformations, particularly map-like transformations followed by filters, differs between RDDs and higher-level abstractions like DataFrames and Datasets. Let’s delve into these differences while analyzing a scenario using both low-level RDDs and structured APIs.</p><p>We will start with a CSV file where we concatenate ‘Phone 1’ and ‘Phone 2’, followed by filtering the resulting data to include only records where the Country name is ‘Chile’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-yuVXg4LzodYSNYS" /><figcaption>Input CSV</figcaption></figure><p><strong>RDD:</strong></p><p><strong>R</strong>esilient <strong>D</strong>istributed <strong>D</strong>ataset is the fundamental data structure in Apache Spark, representing an immutable, distributed collection of objects that can be processed in parallel across a cluster.</p><p>When we perform transformations on RDDs (such as map, filter, reduce), spark creates a Logical Plan and <strong>executes them in the order they are defined</strong>. Each transformation on an RDD results in a new RDD being created, and these transformations are lazily evaluated, meaning they are not computed until an action (like collect() or saveAsTextFile()) is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*duf7Z9HVaNUNphf_" /></figure><p>Since RDD transformations are applied sequentially and eagerly (when actions are triggered), filters and other transformations on RDDs follow the order in which they are written in code. If we examine the DAG below, we can observe that the transformations appear in the same order as they are specified in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kNJQIv0M1yIvjPGf" /><figcaption>RDD DAG</figcaption></figure><p><strong>Structured APIs (DataFrames/Datasets):</strong></p><p>Structured APIs like DataFrames and Datasets in Spark are built on top of RDDs but provide higher-level abstractions that allow Spark to optimize and reorganize operations for better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w86VI-LEeYfFoFPt" /></figure><p>Let’s understand the power of <strong>Catalyst Optimizer</strong>, once the logical plan (which will be nearly identical to that of RDD, involving Concatenation followed by Filtering) is generated, it is passed to catalyst optimizer. This optimizer applies various optimizations and generates an optimized logical plan, which includes:</p><ol><li><strong>Predicate Pushdown</strong>: This optimization involves pushing down filters (predicates) as close to the data source as possible. In our example, we are filtering a DataFrame on a Country column, Spark will try to apply that filter as early as possible in the execution plan.</li><li><strong>Logical Optimization</strong>: Spark may reorder and combine operations to minimize the amount of data shuffled between nodes, optimize join strategies, and so on</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NISEgHj6N9dBASlD" /><figcaption>DataFrame DAG</figcaption></figure><p>Due to Predicate Pushdown, if you check the physical plan or DAG spark pushes the filter operation first followed by concatenation of (“Phone 1 and Phone 2”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FwN2khMKIW8ptK_z" /><figcaption>Physical Plan</figcaption></figure><p><strong>Summary:</strong></p><ul><li><strong>RDDs</strong>: Transformations are applied sequentially and eagerly, following the order in which they are defined in your code</li><li><strong>Structured APIs</strong> (DataFrames/Datasets): Operations like filters are pushed down and optimized by Spark’s Catalyst optimizer, leading to potentially more efficient execution plans.</li></ul><p>Thank you for reading this article. Stay tuned for a deeper dive into the Catalyst Optimizer in our next article.</p><p>If you have enjoyed it, please consider sharing it with your peers and clicking the clap icon below. Your support helps others discover the content too!</p><p>“Millions saw the apple fall. Newton was the only one who asked why. Keep Questioning!!!”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7539d72d5469" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>