<?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 Surender Panchaksharam on Medium]]></title>
        <description><![CDATA[Stories by Surender Panchaksharam on Medium]]></description>
        <link>https://medium.com/@surenderpa?source=rss-b957f9a6088f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*diEx2dvM3AxBPvWUbrCh2A.jpeg</url>
            <title>Stories by Surender Panchaksharam on Medium</title>
            <link>https://medium.com/@surenderpa?source=rss-b957f9a6088f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:33:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surenderpa/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[Nulls behavior in Spark:]]></title>
            <link>https://surenderpa.medium.com/nulls-behavior-in-spark-25e827d6437f?source=rss-b957f9a6088f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e827d6437f</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Surender Panchaksharam]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 13:26:03 GMT</pubDate>
            <atom:updated>2022-10-23T13:26:03.243Z</atom:updated>
            <content:encoded><![CDATA[<p>What are Null values? Null values means no value at all. Null value in PySpark is same as None data type in Python. Note that empty string “” is different from “null” or “None”</p><p>Let us discuss what happens when you do the following operations on a column containing null values</p><ol><li>Dataframe method count versus function count</li><li>Aggregation</li><li>Comparison operations (like greater than or less than)</li><li>join operations</li></ol><p>Let us create a pyspark dataframe</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import count<br>spark=SparkSession.builder.master(&quot;local&quot;)\<br>      .appName(&quot;nulls_with_spark&quot;).getOrCreate()</pre><pre>data=[ (1,&quot;suren&quot;,29,&quot;developer&quot;,40000, 45000),                            (2,&quot;ashok&quot;,24,&quot;manager&quot;,50000, None),<br>(3,&quot;naveen&quot;,29, &quot;&quot;,None, 33000),<br>(4,&quot;sharmi&quot;,28,&quot;manager&quot;,None, None),<br>(None, None, None, None, None, None)]</pre><pre>columns=[&quot;id&quot;,&quot;employee&quot;,&quot;age&quot;,&quot;role&quot;,&quot;salary_2021&quot;, &quot;salary_2022&quot;]</pre><pre>df_employees=spark.createDataFrame(data, columns)<br>df_employees.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*Q7Cf3_cFdA0eQvV8nHLobw.jpeg" /><figcaption>Output of df_employees.show() is seen in the above picture</figcaption></figure><ol><li><strong>Dataframe count method versus function count method:</strong></li></ol><p>Dataframe count method(df_employees.count()) counts null values. function count method do not count null values</p><pre>#dataframe count method below<br>print(&quot;total dataframe row count&quot;,df_employees.count())</pre><pre>print(&quot;employee column count&quot;,df_employees.select(&quot;employee&quot;).count())</pre><pre>#function count method below<br>df_employees.select(count(df_employees.employee)).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*EcejG4n-6pVXCMiKvnRGOw.jpeg" /><figcaption>Dataframe count operation counted null value and returned 5 where as function ignored null and returned 4</figcaption></figure><p><strong>2. Aggregation on a column with null values</strong></p><p>When groupby is applied on a column with null values and empty strings, then each null value in the column are grouped together and empty strings are also grouped together. We can see the count of null values and empty strings in the below example</p><pre>print(&quot;Aggregation on a column with nulls below&quot;)<br>df_employees.groupby(&quot;role&quot;).count().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*Ki15agrZDMZLsYcoCWM-JA.jpeg" /><figcaption>See null value is identified as a group and empty string(row 4, under role column) is also identified as a group</figcaption></figure><p><strong>3. Comparison operations on a columns with null values</strong></p><p>When comparison is made on two columns which contain null values, rows with null values in one of the columns or rows where both columns are null are ignored and those rows are not present in the result dataframe. See that only one row is present in below result though original dataframe “df_employees has 5 rows</p><pre>print(&quot;comparison operations on two columns with nulls below&quot;)<br>df_employees.filter(<br>df_employees.salary_2022 &gt; df_employees.salary_2021).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*oa9ZMnJtC1HA84-u82_VTA.jpeg" /><figcaption>rows with null values are ignored in the null operation</figcaption></figure><p><strong>4. Join operation on column with null values</strong></p><p>When you join on column with null values, then rows with null values are ignored on both sides of the table. Notice that even though there are nulls in both columns they are not matched but ignored</p><p>Let us create a new dataframe for the join operation</p><pre>city_data = [(1,&quot;chennai&quot;),(2,&quot;Trivandrum&quot;),(3,&quot;salem&quot;),<br>           (4,&quot;chennai&quot;),(None, None)]</pre><pre>columns_location =[&quot;id&quot;, &quot;city&quot;]</pre><pre>df_location = spark.createDataFrame(city_data, columns_location)</pre><pre>df2=df_employees.join(df_location,on=[&quot;id&quot;], how=&quot;inner&quot;)<br>df2.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*1tn6DqGKyypYBRnaPfLhHA.jpeg" /><figcaption>Joined table df2. Null values of Id column are ignored from both the tables</figcaption></figure><p>Hope you found this useful! let me know your thoughts</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e827d6437f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark Optimization Techniques]]></title>
            <link>https://surenderpa.medium.com/apache-spark-optimization-techniques-b7ced0b9c218?source=rss-b957f9a6088f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ced0b9c218</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineer]]></category>
            <dc:creator><![CDATA[Surender Panchaksharam]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 16:32:52 GMT</pubDate>
            <atom:updated>2023-09-26T03:20:03.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Below are Spark optimization techniques which would reduce your data processing time and make your spark applications more efficient</p><ol><li><strong>Caching</strong>: Spark Cache is used to save frequently used dataframes to avoid re-computation. Caching saves your data in memory or to disk .Spark provides two functions <strong>Cache </strong>and <strong>Persist</strong>. Cache function saves your dataframe to memory and if spilled then to disk. Persist function gives you an option to specify where to cache your data and we can cache in memory or disk. We need to be careful with the amount of data being cached in memory because cached data would occupy your compute memory and you may want to make sure you have sufficient compute memory to process your data. Persisting the cache on disk can be considered since it would not occupy your compute power. It is also a good practice to unpersist the cached dataframe using the unpersist() method once the computations are completed. Note that it is not recommended to cache a table just read using “spark.read” command because catalyst optimizer cannot apply query optimizations like predicate pushdown on a cached dataframe</li><li><strong>Optimize shuffle partition: </strong>It is duty of the spark developer to set the shuffle partition for every spark application. Default partition size is 200. In most cases we can set the shuffle partition proportional to the number of cores in the cluster.</li><li><strong>Use Higher order functions and avoid UDF’s: </strong>Use Spark SQL functions wherever possible and avoid UDF’s because incase of Pyspark, Since there is code serialization between Python and Java at every executor which will slow down the query performance</li><li><strong>Enable AQE: </strong>Adaptive Query Execution is a new feature introduced in Spark 3.0 and enabled by default from Spark 3.2. AQE provides faster query performance by allowing Spark to change the query plan at run time while the query is being executed.This feature can be turned ON using spark.conf.set (“spark.sql.adaptive.enabled”, True). When AQE is ON, based on the runtime statistics, spark knows the size of data in shuffle files. So, when working out the query execution plan at query run time, it can switch join strategies to choose between shuffle sort join or broadcast join based on the size of the tables at run time, coalesce the number of shuffle partitions or optimize the skew joins.</li></ol><p><strong>The 3 advantages of Adaptive Query Execution:</strong></p><p><strong>Join Strategy switch:</strong></p><p>If you have a JOIN condition in your query then while making the initial query plan, spark will read the size of table (data not loaded yet) and if one of the table has a size less than 10 MB then Broadcast Join(table is pushed to all the executors’ memory. No data shuffle during join) is used . Else usual sort-merge join is used (Sort merge join causes data shuffling between nodes which is expensive)</p><p>AQE enables Spark to modify the physical query plan at run time using the run time statistics. When the query is executed, initially spark may have chosen sort-merge join based on scanning the two table sizes being joined since table sizes are more than 10MB. But at run time, spark does predicate push down where filters are applied directly on the data source, this may reduce size of table being loaded to less than 10 MB. In this case, if AQE is enabled then spark can alter the query plan and change the sort-merge join to Broadcast JOIN which will boost the query performance</p><p><strong>Coalesce Shuffle partition:</strong></p><p><strong>spark.sql.shuffle.partitions </strong>should be set by developer for every job. Every wide partition will output partitions equal to the set number of shuffle partitions. Default value is 200. We can set spark shuffle partitions proportional total number of cores in the cluster. More on this discussed later in this blog</p><p>If AQE is ON, then spark will choose the optimal shuffle partition itself based on run time statistics.</p><p><strong>NOTE</strong>: Set a higher shuffle partition proportional to the total number of cores in the cluster so that spark can automatically scale down the shuffle partition based on run time statistics (AQE needs to be ON).</p><p><strong>Optimize Skew Joins:</strong></p><p>Data Skew occurs when the data is unevenly distributed among the data partitions in memory.</p><p>If AQE is turned ON, spark can detect skewness from shuffle file statistics while the query runs and it can sub-partition the skewed data so that each task would complete at the approximately the same amount of time</p><p>5. <strong>Broadcast join:</strong> Broadcast join distributes the complete table (which is of small size usually less than 15 MB) to all the worker nodes. Since the complete table is present on all the worker nodes, there is no data shuffle resulting in improved performance. Default broadcast size set by Spark is 10 MB and same can be altered using the command</p><p>Spark.conf.set(“spark.sql.autoBroadcastJoinThreshold”, 10MB)</p><p>Broadcast join speeds up the join operation by avoiding shuffle. It is advantageous to broadcast tables of size only around or below 100MB.</p><p>Spark can choose the optimal join itself if Adaptive Query Execution (AQE) is turned ON</p><p>6. <strong>Avoid Skew and Spill: </strong>Skew is a condition where one of the data partition is of very large size. This will make the task to run longer than the other task and the the stage will complete only after the skewed data partition is processed. Skew may also result in spill if there is no sufficient executor memory. Spill is a condition where spark writes the intermediate data to disk since there is no available memory. Skew can be avoided if AQE is turned ON and spill can be avoided by making sure there is enough Spark memory. Skew and spill can be detected in the Spark UI</p><p>7. <strong>Avoid scanning issue:</strong></p><p>Register highly partitioned files as tables. Highly partitioned files, for example a file with year, month and days columns which is partitioned on the same year, month and days column, it is better to register them as tables so that table meta data are already registered in the meta store resulting in faster query performance. Also avoid too many small files (ex 100s of parquet part files of very small size) by combining them to a single file using functions like coalesce. Small files would make queries slower since spark would take more time to scan the files in the folder</p><p>8. <strong>Bucketing:</strong></p><p>Bucketing is a mitigation strategy to avoid expensive shuffle operations for tables of size in terabyte range or more. Predominantly used to join terabyte sized tables</p><p>Bucketing should only be used for datasets in range of terabytes or more where the tables will be queried /joined frequently</p><p>Bucketing pre-shuffles the data so that data is located in specific partition or part files. Location of part files and content of part files are tracked by the meta-store</p><p>when bucketing two tables which are frequently joined, then both tables should be bucketed on the same column with same number of buckets even if one table is in terabytes range and other table is in MB range</p><p>Number of spark partitions while reading the file from disk is equal to the number of buckets on the dataset. Note that defaultMaxPartitionBytes is ignored to calculate the partitions here</p><p>Bucketing is only useful when you are joining two tables very frequently to avoid shuffle. Note that you are pre-shuffling the data to get the data bucketed and then doing a join operation on the bucketed data for the improved query performance. So, if you are a joining the table only once then you might be better off without bucketing</p><p>9. <strong>Disk partitioning:</strong></p><p>The advantages of disk partition are predicate pushdown where spark would read only the necessary columns and rows from the file which gives significant performance gain . The other advantage is reduced IO because column names and data types are inferred from the subdirectories. Both are finalized during scanning and NOT when reading the actual data. IO is reduced since the columns values are inferred from directory name itself instead of having to read through every single record</p><p>Disk partition for low cardinality columns like Years, months and date where filters fetches a group of records. Disk partition helps to apply predicate push down and reduced IO since the partition column values can be inferred from the directory and sub-directories instead of having to read the part files</p><p>10. <strong>Z-order indexing:</strong></p><p>Z-ordering is a technique which sorts the data in delta tables. Z-ordering provides quick query performance by reading only necessary data files which are needed for your query while skipping others.</p><p>Z-ordering reduces the scan time for highly selective queries. (example: filtering a record which happened only once on a dataset containing billion records).</p><p>You can use z-order for any number of columns. But we should order the columns based on columns most used in your queries. Adding more columns will decrease the performance of z-ordering</p><p>Z-ordering code example below</p><pre>-- SQL <br>OPTIMIZE events<br>WHERE date &gt;= current_timestamp() - INTERVAL 1 day<br>ZORDER BY (eventType,date)</pre><p><strong>11.</strong> <strong>file format selection:</strong></p><p>Prefer Columnar formats when you need quick reads and Row formats for quick writes. Row based file formats like AVRO offer faster write but slower reads and on the other hand, columnar file formats like ORC and Parquet offer slower writes when compared to AVRO but has faster read performance. Row based file format are used for files that are written and read once. Columnar file formats are used for files which are read and transformed more frequently.</p><p>Parquet is most used file format in Spark and provides faster query performance using data skipping and data are always compressed on storage saving storage space. Data skipping is a process where Spark can read only necessary rows and columns from the parquet file to process a query instead of having to read the entire file</p><p>12. <strong>Pass Schema manually:</strong></p><p>Pass the schema manually whenever possible. Because spark will have to scan entire files in case of CSV and JSON file format to infer the schema. Even in case of parquets, spark will have to read at least one part file to infer the schema.</p><p><strong>13. filter rows and columns as early as possible</strong></p><p>Apply filters to have only necessary rows and select only necessary columns before doing transformations on the data. This would reduce the processing time and necessary compute power</p><p>I hope you found this useful! let me know in the comments section if I have to add any other important optimization techniques to this blog</p><p>14. Databricks Disk Cache (Delta cache):</p><p>Disk cache is databricks proprietary feature which saves parquet files in cluster node’s local disk when you read a parquet file from remote source like S3/ADLS and subsequent read of the data would be fetched from node’s local disk and not read from remote source</p><p>This feature is automatically enabled by databricks and is useful when you choose cluster nodes with SSD based local storage . Check if disk cache is enabled using the below command</p><pre>spark.conf.get(&quot;spark.databricks.io.cache.enabled&quot;)</pre><p>For more info on disk cache, refer this <a href="https://docs.databricks.com/en/optimizations/disk-cache.html">databricks </a>blog</p><p>Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ced0b9c218" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>