<?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 Abid Merchant on Medium]]></title>
        <description><![CDATA[Stories by Abid Merchant on Medium]]></description>
        <link>https://medium.com/@merchantabid4?source=rss-9cea112ffd4e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vxUMA-wH0ASa35IHpWerdQ.jpeg</url>
            <title>Stories by Abid Merchant on Medium</title>
            <link>https://medium.com/@merchantabid4?source=rss-9cea112ffd4e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:19:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@merchantabid4/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[Movie Recommendation with Collaborative Filtering in Pyspark]]></title>
            <link>https://medium.com/analytics-vidhya/movie-recommendation-with-collaborative-filtering-in-pyspark-8385dccecfca?source=rss-9cea112ffd4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8385dccecfca</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[sparkml]]></category>
            <category><![CDATA[spark-mllib]]></category>
            <category><![CDATA[movie-recommendation]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <dc:creator><![CDATA[Abid Merchant]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 18:48:56 GMT</pubDate>
            <atom:updated>2020-07-27T12:56:52.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*7x_wVI-ndHoSxU0R0r0JJQ.jpeg" /></figure><p>Hey Fellas,</p><p>Today we will explore a cool Machine Learning algorithm known by the name “<a href="https://spark.apache.org/docs/latest/mllib-collaborative-filtering.html">Collaborative Filtering with ALS</a>” which is typically used to recommend a movie/song or any feature based on user and the user’s preference of movie (judged by ratings given by that user). This Algorithm is used by many renowned <a href="https://en.wikipedia.org/wiki/Collaborative_filtering#Application_on_social_web">companies like Youtube, Reddit, Netflix</a> and me(for article :P). Cool isn’t it.</p><p>So basically, Collaborative Filtering model takes userId, item column and ratings column as feature columns and trains itself to recommend items for each user. So, lets not waste much time on the boring theoretical part and jump into the fun coding part. Still, if you want to read more about the Algorithm you can visit <a href="https://databricks.com/blog/2014/07/23/scalable-collaborative-filtering-with-spark-mllib.html">here</a>.</p><p>Now, let’s begin! I will be using publicly available dataset for movies which can be found <a href="https://grouplens.org/datasets/movielens/">here</a>. So, firstly lets read and display the data.</p><pre>ratings = spark.read.option(“inferSchema”,True)\<br>                    .option(“header”,True)\<br>                    .csv(“ml-latest-small/ratings.csv”)</pre><pre>ratings.show(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*3fxuUGDbcmwYCPgttpgbcQ.png" /><figcaption>Movie Dataset</figcaption></figure><p>Now lets move forward and initiate our ALS model and also split our dataset into two parts for training and testing (de facto 80:20 ratio).</p><pre>from pyspark.ml.recommendation import ALS</pre><pre>als = ALS(maxIter=10, regParam=0.5, userCol=&quot;userId&quot;, <br>                      itemCol = &quot;movieId&quot;, ratingCol =    &quot;rating&quot;, coldStartStrategy = &quot;drop&quot;)</pre><pre>train, test = ratings.randomSplit([0.8, 0.2])</pre><p>Just a quick overview of parameters used, the three parameters userCol, itemCol and ratingCol is for setting features, maxIter is for number of iterations ALS will do (can be decided as per use case), regParam specifies the regularization parameter in ALS (default is 1.0) and <a href="https://spark.apache.org/docs/2.2.0/ml-collaborative-filtering.html#cold-start-strategy">coldStartStrategy</a> means when prediction is run and a model is not trained for a particular user/ ratings or items are not found for a user then it will drop those users if given “drop” as parameter’s value.</p><p>So, now lets train our model and generate predictions.</p><pre>#Training the Model<br>alsModel = als.fit(train)</pre><pre>#Generating Predictions<br>prediction = alsModel.transform(test)</pre><pre>prediction.show(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*Fx8zb9nASNE0CBiXu8u3JQ.png" /><figcaption>Prediction Generated</figcaption></figure><p>So, some prediction seem accurate but some suck(let’s be frank :P), anyways now that our model is trained, let’s check how good it is.</p><pre>from pyspark.ml.evaluation import RegressionEvaluator</pre><pre>evaluator = RegressionEvaluator(metricName=&quot;mse&quot;, labelCol=&quot;rating&quot;,  predictionCol=&quot;prediction&quot;)</pre><pre>mse = evaluator.evaluate(prediction)</pre><pre>print(mse)</pre><pre>Output: 1.0168009658367847</pre><p>Hmm, accuracy is also not bad(unnecessary judged the model at start). So, the model seems to working quite well. So let’s ask him to recommend top 3 movies for every user.</p><pre>recommended_movie_df = alsModel.recommendForAllUsers(3)</pre><pre>recommended_movie_df.show(10, False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*7JbWimsTEL7R4yZkpcH94g.png" /></figure><p>The output comes as a list of recommendations for each user which can easily be transformed columns. You can also pass the dataset and generate recommendations for it by using <em>recommendForUserSubset()</em> function.</p><p>So, that’s all from my side for this one. Hope you would have liked my article, if any suggestions please comment below. Do checkout my previous articles as well, link is given below:</p><p><a href="https://medium.com/analytics-vidhya/spark-delta-lake-d05dd480287a">Spark Delta Lake</a></p><p>So, see you next time, ta ta, bella ciao!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8385dccecfca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/movie-recommendation-with-collaborative-filtering-in-pyspark-8385dccecfca">Movie Recommendation with Collaborative Filtering in Pyspark</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Questions you can expect in Spark Interview]]></title>
            <link>https://medium.com/analytics-vidhya/10-questions-you-can-expect-in-spark-interview-24b89b807dfb?source=rss-9cea112ffd4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/24b89b807dfb</guid>
            <category><![CDATA[spark-qa]]></category>
            <category><![CDATA[spark-interview-question]]></category>
            <category><![CDATA[spark-dataframe]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[rdd-vs-dataframes]]></category>
            <dc:creator><![CDATA[Abid Merchant]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 07:19:17 GMT</pubDate>
            <atom:updated>2019-12-17T08:26:08.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Questions frequently asked in Apache Spark Interviews</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*Ia_HE0ajwzMizANGH_ZQrA.png" /></figure><p>Hey Fellas,</p><p>Data Engineer position is highly in demand in recent times, with Apache Spark being state of the art for Batch processing and ETL, being cognizant in it can easily land you a job as a Data Engineer. So, in this article I will be showcasing 10 questions you can expect in Apache Spark Interview, please note that I won’t be including naive questions like “What is Dataframe?”, “What is Spark RDD?” or “How to read/write orc file?” as I expect that an associate going for a job interview for Apache Spark would be knowing these things already and reiterating them again is pointless.</p><p>So all these said, let’s jump to Q/A.</p><h4>Is Spark Better than Hadoop? Why?</h4><p>Yes Spark is evidently better than Hadoop, one of the major reason is it is faster than Hadoop because of in memory processing which helps reduce latency for read/write operations. Basically when we use map reduce paradigm, on completion of each task there will be write on disk and when the data has to be used again, read will be performed again. But, in Spark the processing will be done in memory and the dataframes are cached for future use which results in increased performance. Moreover, Spark comes with libraries like Spark ML, Spark SQL, Spark Streaming which makes it more rich.</p><h4>What is difference between coalesce and repartition?</h4><p>This is the hotshot topic of discussion when it comes to optimising your spark job. Both functions basically allows us to manipulate the number of partitions of our dataframe, but there uses are different. Repartition will do full shuffle on the data so we can increase or decrease the number of partitions, but coalesce will just shift you data from one partition to other binding us to only decrease number of partitions using it. Coalesce will be faster as shuffle will be less but if the number of partitions has to be increased or the data is skewed and we want to decrease number of partition by reshuffling, then we should go with repartition method.</p><h4>What is Broadcast Join?</h4><p>Broadcast join is also used for optimizing Spark Job(particularly joins). When small sized dataframe is joined with relatively larger dataframe, we can broadcast small dataframe which will send a copy of the small dataframe to each node which will result in faster join execution and less shuffling. Syntax is given below.</p><pre>import pyspark.sql.functions as fn<br>final = big.join(fn.broadcast(small),[&quot;common_id&quot;])</pre><p>When broadcasting smaller dataframe, we can reduce its partition to 1 for better performance(depending on your use-case).</p><h4>What is lazy evaluation?</h4><p>There are two important aspects in Apache Spark, one is action and second is transformation. Transformation includes functions like filter,where,when, on calling these functions Spark does not actually performs those transformations but are stacked until an action is called. When an action is called all the transformations are executed at that point, this helps Apache Spark to optimise the performance of the job. Example of actions are show(), count(), collect().</p><h4>What is the difference between cache() and persist()?</h4><p>Both of the Api’s are used to persist dataframes in memory at different levels, but in persist we can specify the Storage level as MEMORY_ONLY, MEMORY_AND_DISK, DISK_ONLY etc whereas in cache() we cannot specify the storage level and is considered MEMORY_ONLY by default.</p><h4>Difference between Rank and Dense Rank?</h4><p>This a sql question but I included it because we can expect this question if we go in window-partition section. Suppose, we have a dataset as given below:</p><pre>Name  Salary  Rank  Dense_rank<br>Abid  1000     1      1<br>Ron   1500     2      2<br>Joy   1500     2      2<br>Aly   2000     4      3<br>Raj   3000     5      4</pre><p>Here salary is in increasing order and we are getting rank() an dense_rank() for the dataset. As Ron and Joy have same salary they get the same rank, but rank() will leave hole and keep “3” as empty whereas dense_rank() will fill all the gaps even though same values are encountered.</p><h4>How to connect Hive through Spark SQL?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*pLnszelEZuWaBOeUWjsXxg.png" /></figure><p>Solution to this is to copy your hive-site.xml and core-site.xml in spark conf folder which will give Spark job all the required metadata about Hive metastore and you have to enable Hive Support along with specifying your warehouse directory location of Hive in configuration while starting your Spark Session as given below:</p><pre>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;Python Spark SQL Hive integration example&quot;) \<br>    .config(&quot;spark.sql.warehouse.dir&quot;, warehouse_location) \<br>    .enableHiveSupport() \<br>    .getOrCreate()</pre><p>To read in detail about this visit <a href="https://spark.apache.org/docs/latest/sql-data-sources-hive-tables.html">here</a></p><h4>Is RDD better than Dataframes?</h4><p>No, Dataframes are faster in execution than RDDs and it is more easier syntactically. One doubt you might get is Dataframes is converted to RDDs in backend then how is RDD slow? The answer is Dataframe uses Catalyst Optimizer which makes it run faster than RDDs on the other hand RDDs don’t use any optimizer during execution. The comparison between these Api has been explained in detail in <a href="https://www.youtube.com/watch?v=Ofk7G3GD9jk">this video</a> at Spark Summit 2017.</p><h4>How to read an xml file in Spark?</h4><p>This is very simple, spark has <a href="https://mvnrepository.com/artifact/com.databricks/spark-xml_2.10/0.2.0">spark-xml</a> package which allows us to parse xml files to dataframes, consider the xml file given below:</p><pre>&lt;person&gt;<br>    &lt;name&gt;John&lt;/name&gt;<br>    &lt;address&gt;Some more Data&lt;/address&gt;<br>&lt;/person&gt;</pre><p>Then to read the we can specify schema and root tag during read as follows:</p><pre>xmlDF = spark.read<br>      .format(&quot;com.databricks.spark.xml&quot;)<br>      .option(&quot;rootTag&quot;, &quot;person&quot;)<br>      .option(&quot;rowTag&quot;, &quot;name&quot;)<br>      .option(&quot;rowTag&quot;, &quot;address&quot;)      <br>      .xml(&quot;yourFile.xml&quot;)</pre><p>This will give you dataframe with “name” and “address” as columns.</p><h4>Do you need to install Spark on all nodes of the YARN cluster while running Spark on YARN mode?</h4><p>No, it is not necessary to install Spark on all nodes when submitting job through YARN mode as Spark runs on top of YARN and uses YARN engine to get all the required resources, we have to install Spark only on one node. Read more about YARN deployment mode <a href="https://spark.apache.org/docs/latest/running-on-yarn.html">here</a>.</p><p>So, that’s all folks hope you find my article helpful. Do checkout my previous article on Spark Delta in which I have explained ACID on spark. Till then ta ta!</p><p><a href="https://medium.com/analytics-vidhya/spark-delta-lake-d05dd480287a">Spark Delta Lake</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24b89b807dfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/10-questions-you-can-expect-in-spark-interview-24b89b807dfb">10 Questions you can expect in Spark Interview</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things to care before “Productionizing“ Apache Spark]]></title>
            <link>https://medium.com/analytics-vidhya/things-to-care-before-productionizing-apache-spark-816a6bed3c6a?source=rss-9cea112ffd4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/816a6bed3c6a</guid>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Abid Merchant]]></dc:creator>
            <pubDate>Sat, 23 Nov 2019 19:31:40 GMT</pubDate>
            <atom:updated>2019-12-24T07:31:31.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*AMn9eZYccSC4erz-9XJgiQ.png" /></figure><p>After inception of Apache Spark in 2015 there has been no stopping to it, with most Tech Giants embracing this technology it has been state of the art for unified Data Processing. Moreover, it comes with Spark Mllib library which makes it one shop stop for Data Engineering and Data Science projects for large scale Data analysis. But, apart from Spark being Fast, Robust and really cool it has some loopholes which gave me a tough time at my work and so have decided to put up a list of challenges we face in spark and most of the impediments can be easily overcome if known prior.</p><h4>Null Pointer Exception</h4><p>This exception is my worst nightmare and I literally mean it, many of us would have faced this exception. It took me almost 3 days to debug and reach to the exact issue and still a small mistake in code can lead to this problem. Let me show you how this issue comes in logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*hxDB0OlFHGZwsqkXsAyg7w.png" /></figure><p>Encountering this issue, my first thought was checking Null rows or some null data in columns where nulls are not allowed. But, after so much toil and trouble I thought of going down to file structure and check the files. After some debugging I got to know that the issue comes when there is mismatch in datatype in column. To throw some more light on the issue, let me show the code I used to recreate the exception</p><pre>import pyspark.sql.functions as fn</pre><pre>df = spark.range(1,5)</pre><pre>df.write.orc(&quot;/mnt/data/nullPointer&quot;)</pre><pre>df1 = df.withColumn(&quot;id&quot;, fn.lit(&quot;id&quot;).cast(&quot;String&quot;))</pre><pre>df1.write.orc(&quot;/mnt/data/nullPointer&quot;, mode=&quot;append&quot;)</pre><pre>new = spark.read.orc(&quot;/mnt/data/nullPointer&quot;)</pre><pre>new.show()</pre><p>So, basically I created a dataframe with column having data in integers and overwrote to a folder, on the same data I appended same column with “String” datatype, on writing Spark gave me no issue as Spark follow “Schema on Read” and don’t care what type of data goes into Data Lake. When I read the data it gave me no issue, even on performing some operations like count(), show() it might not give you issue as show() might take data from only one partition and count() will just count the rows. But issue might come, when you try to aggregate data of that column or you show more rows and in that case you might encounter this exception and you might be clueless just like me and start meddling with the data which will not get you any near to real issue which is at storage level where data is corrupted.</p><p><em>Resolution: </em>This type of issue might come when you have delta loads and data is handled in different scripts, so every time make sure you cast your variables and datatypes of each column are in sync. Once you face this issue, even I don’t know how to get the data back, only work around I got is recreating the table in Hive as Hive will be able to read the data even though datatypes is files are not matching.</p><h4>Broadcast Exception</h4><p>This issue is very rare if you are working on small datasets. I faced this issue very few types but still when something is going to be in production, we have to make sure each of its last bit is in proper position. This issue comes when you broadcast join a table and it takes very long for broadcasting. There is a default threshold time if it exceeds that, your script will raise an exception.</p><p><em>Resolution</em>: You can initially increase the timeout for broadcast if you suspect that the dataframe you are broadcasting is large</p><p>spark.conf.set(&quot;spark.sql.broadcastTimeout&quot;, valueAsPerYourNeed)</p><p>You can set it to “-1” for infinite time.</p><h4>OutOfMemoryError: Java heap space</h4><p>This issue is very common for me considering the dataset I meddle with. Seeing this issue the first obvious resolution is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*tTLt2pD971keEhMuPu2GVQ.jpeg" /></figure><p>And the answer was not incorrect fully and I increased the memory for my job and it worked for me, but some days later I again got the same issue and there is a certain extent you can increase resources for a single job, so I found another resolution to it.</p><p><em>Resolution: </em>Firstly you can try to increase memory using below command</p><pre>spark-submit --num-executor 5 --total-executor-cores 30 --driver-memory 5G(to be increase) --executor-memory 5G(to be increased)</pre><p>Another resolution is you can debug an find the dataframe whose transformation is getting the issue, and increase the number of partitions using below command:</p><pre>df_repart = df.repartition(500) #as per you requirement</pre><p>Default is “200” and can be increased as per your need. Increase number of partitions will reduce load at each executor resulting in more stable job execution.</p><p>Apart from these here is a list to make sure of issue before going to production:</p><ul><li>Overwriting on same file is not allowed in Spark, it will delete your data then will give you an exception(very frustrating at times!).</li><li>Append on empty file will raise an exception.</li><li>Make a separate config file for your url or you will die changing it while going to new environment.</li></ul><p>So to conclude, Apache Spark is a very powerful tool and having it as a part of your project will reap you performance improvements but it has some flaws and the list I created in not exhaustive. So, we have to be agile and preemptive to create seamless Spark jobs.</p><p>Moreover, some of the issues are now solved with Delta Lake coming into picture from 2019 giving a new dawn to ACID operations in Spark. If you want to know about it check out this article.</p><p><a href="https://medium.com/@merchantabid4/spark-delta-lake-d05dd480287a">Spark Delta Lake</a></p><p>So that’s all folks, if you like my article don’t forget to give it a clap and to follow me for more exciting articles. Till then good bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816a6bed3c6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/things-to-care-before-productionizing-apache-spark-816a6bed3c6a">Things to care before “Productionizing“ Apache Spark</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting hands dirty in Spark Delta Lake]]></title>
            <link>https://medium.com/analytics-vidhya/getting-hands-dirty-in-spark-delta-lake-1963921e4de6?source=rss-9cea112ffd4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1963921e4de6</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[merge-in-spark]]></category>
            <category><![CDATA[acid-on-spark]]></category>
            <dc:creator><![CDATA[Abid Merchant]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 21:06:50 GMT</pubDate>
            <atom:updated>2019-12-24T07:33:35.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the world of Delta Lake from with Hands On</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*vxgVZ4LubyxAW43YYH8Law.jpeg" /></figure><p>Hey Fellas,</p><p>This is 2nd part of my article in which I gave an overview of Delta Lake and its use cases, In case you happen to come directly here do give my first article a read to get some context. Here’s the link</p><p><a href="https://medium.com/@merchantabid4/spark-delta-lake-d05dd480287a">Spark Delta Lake</a></p><p>So, In this article we will go through the amazing work Delta Lake does, the code is in Pyspark. Firstly, let’s see how to get Delta Lake to out Spark Notebook.</p><pre>pip install --upgrade pyspark</pre><pre>pyspark --packages io.delta:delta-core_2.11:0.4.0</pre><p>First command is not necessary if you already have an upgraded spark, second command will start our pyspark shell with Delta package, Voila! nothing more to do for installation part. Please note that minimum Spark version required for Delta lake is Spark 2.4.2.</p><p>So, as per my previous article Delta Lake brings to us the following important operations:</p><ul><li>Schema Enforcement</li><li>ACID transactions on Data Lake</li><li>Time Travel Capabilities</li></ul><p>We will go each of these functionalities, first lets understand Schema Enforcement.</p><h3>Schema Enforcement</h3><p>As I said, with Delta Lake “schema on write” is followed, so any changes in schema when writing will be tracked and any discrepancy will raise an exception at that time. Below code will make a dataframe of 1–5 numbers and we will write it as a Delta table.</p><pre>data = spark.range(1,5)<br>data.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(&quot;/mnt/data/delta_sample&quot;)</pre><p>Lets checkout the output file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*KqNg5qFiZgmNAPwQ4FBXkg.png" /></figure><p>As you can see write format is parquet. A log file is maintained which will contain all the transaction log. The log file is a JSON file which will containf metadata regarding the operations performed on our dataset and this log file will be read by spark first rather than directly reading the part files.</p><p>Now, I will make a dataframe with numbers from 5–10 and will give its datatype as String and will try to append the dataset on our existing dataset.</p><pre>import pyspark.sql.functions as fn<br>new_data = spark.range(5,10)<br>new_data = new_data.withColumn(&quot;id&quot;,fn.col(&quot;id&quot;).cast(&quot;String&quot;))<br>new_data.write.format(&quot;delta&quot;).mode(&quot;append&quot;).save(&quot;/mnt/data/delta_sample&quot;)</pre><p>Performing below snippet of code led me to error which mentioned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*VscMxQ2RmjyySgJQuxoI3g.png" /></figure><p>So, Delta lake stopped the incorrect data to go in our delta Lake, moreover on changing my column name from “id” to “id1”, I got another exception. So, as a whole any changed will not be allowed while writing to any existing dataset. Finally, I will append the dataset with correct schema.</p><pre>new_data = spark.range(5,10)<br>new_data.write.format(&quot;delta&quot;).mode(&quot;append&quot;).save(&quot;/mnt/data/delta_sample&quot;)</pre><p>Now, my dataset contains following files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*OZrKosgyMwNchqVhEUzExQ.png" /></figure><p>Let’s take a look at the log file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*XtYAHlA2oEL1heF0ZTnp2g.png" /></figure><p>So, and new log file is generated when I wrote my dataset, the log file contains following content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5dnzqEHumU4ZuVfSX03rQ.png" /></figure><p>It directs spark to add the part files which were newly written on dataset along with specifying information such as mode of write and modification time.</p><p>So, this is how schema on write is enforced and Delta Lake table works. Now, we will dig deeper and understand Merge, Update and Delete operations in Spark.</p><h3>Deletion</h3><p>Now, before performing the delete operation, lets read our table in Delta format, we will read the dataset we just now wrote. Follow the below lines of code.</p><pre>from delta.tables import *</pre><pre>delta_df = DeltaTable.forPath(spark, &quot;/mnt/data/delta&quot;)</pre><p>Delta_df is of type Delta table, we cannot perform spark dataframe operations on it, but that can be achieved by converting it into Spark Dataframe through delta_df.toDF() operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*rr5jJR_-pdKd0S6ILs_dJA.png" /></figure><p>Now, we will delete the data where id is ≤2.</p><pre>delta_df.delete(&quot;id&lt;=2&quot;)</pre><p>That’s it, Delta tables are <strong><em>auto refresh </em></strong>and any changes on the data we do here will directly be reflected on our dataset. So, just after performing the above delete operation, someone on another session reads our dataset will not find id≤2. After deletion, one more commit log was created, let’s checkout how the commit log is written for delete operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X0HcEd2Y13eeSYNrPH4QA.png" /></figure><p>It guides spark to delete the original part files through remove and then add the new part file with predicate as id≤2, even operation performed(DELETE) is specified. So, the commit log is exhaustive and one shop stop for all the metadata of our dataset. Now, we will do updation on the dataset.</p><h3>Updation</h3><p>Now, in this segment we will try out the update operation on our data. We will read the dataset again and will update the value from 5 to 500. Checkout the code snippet for update operation</p><pre>delta_df = DeltaTable.forPath(spark, &quot;/mnt/data/delta&quot;)<br>delta_df.update(condition = &quot;id = 5&quot;, set = { &quot;id&quot;: &quot;500&quot; })\</pre><p>The above operation is will set id to 500 where it is 5 and not to mention that as Delta Table is auto refresh the data is updated. As you can see the syntax is very simple and even a layman will understand it on the first go. So, we move to our final operation Merge.</p><h3>Merge</h3><p>Now, we will perform the merge operation on our Delta Table. Before performing Merge, I will read a new dataset containing Country, Year and Temperature columns and will write it as a Delta Table.</p><pre>df = spark.read.csv(&quot;/mnt/data/dataset&quot;, inferSchema=True, sep=&#39;,&#39;, header=True)</pre><pre>df.write.format(&quot;delta&quot;).save(&quot;/mnt/data/delta_merge&quot;)</pre><p>Our Delta table contains following data…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*SKtWr5uN52lUQJC5-Csg_Q.png" /></figure><p>Now, we have delta feed that has to be merged into this Delta Table in a Spark Dataframe, the data is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*rVHIvIl_CuJomGR1FN0Mew.png" /></figure><p>We received 2 new records out of which <em>Australia </em>is to be added and <em>India </em>has to be merged into our Delta Table.</p><pre>delta_merge.alias(&quot;delta_merge&quot;).merge(<br>    updatesDf.alias(&quot;updates&quot;),<br>    &quot;delta_merge.country = updates.country&quot;) \<br>  .whenMatchedUpdate(set = { <br>        &quot;temperature&quot; : &quot;updates.temperature&quot;,<br>        &quot;year&quot; : &quot;updates.year&quot;<br>  } ) \<br>  .whenNotMatchedInsert(values =<br>    {<br>      &quot;country&quot;: &quot;updates.country&quot;,<br>      &quot;year&quot;: &quot;updates.year&quot;,<br>      &quot;temperature&quot;: &quot;updates.temperature&quot;<br>    }<br>  ) \<br>  .execute()</pre><p>The merge syntax closely resembles to merge syntax in Hive. Firstly, we have given our table table an alias as “delta_merge” and our Spark Dataframe as “updates”. Now, where country column is matched in both the dataset’s, we will updated the temperature and year column from Spark Dataframe to our Delta Lake and when not matched we will insert all the columns into our Delta Lake, simple isn’t it!</p><p>Final merged records will look like…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*YWonFa7pYhL-5FRmg5EqUQ.png" /></figure><p>So, temperature of India got updated to 100.0 and year got updated to 2019 and that’s all about the Merge Operation.</p><h3>Time Travel</h3><p>This is the coolest part of Delta Lake. As explained in my first article, with Delta Lake we will be able to maintain different versions of our dataset’s and can be reused when needed. In this section we will have a closer look as to how we can get different versions of our dataset.</p><p>Before explaining how to get any version of data, first I will show you how to know which version data I have to get, but how will I know when I last updated my data, what I updated and how many versions are actually created? To know that, Delta Table maintains a history which can be get by calling history() method which will return a Spark Dataframe so we can query it and know the version we want to get. History data will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*ZYckr43SxWQlZoNCJdY1ag.png" /></figure><p>So, as you can see it contains each detail we need to understand the operations done on our data. Now, I will read the dataset created by us intially which contained only one column “id” consisting of numbers. We played around with that dataset but while doing so all our activities were tracked and nothing was unseen by Delta Lake. Without further ado I will read the dataset.</p><pre>delta_df = DeltaTable.forPath(spark, &quot;/mnt/data/delta&quot;)</pre><p>Final version of our dataset contained:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*8rNV0k_LtOflAwOZeQJUsw.png" /></figure><p>Now, I will get the dataset of “version 1&quot; and as the history table displays, we had append data to our existing dataset, and if you can travel back in your mind we appended 5–10 numbers to our dataset. So, now lets get that data in out Spark Dataframe:</p><pre>version_1 = spark.read.format(&quot;delta&quot;).option(&quot;versionAsOf&quot;,1).load(&quot;/mnt/data/delta&quot;)</pre><p>This will give us the data consisting from numbers from 0-&gt;9 in Spark Dataframe, you can specify version you want and get your lost baby back in stroller to play around.</p><p>Apart from these things, one more important feature of Delta Lake is deleting the old version data after some time. Cause, we don’t want our storage system to blast after certain period of time. For that, we have function known as vacuum() which will recursively delete files and directories in the table that are not needed by the table for maintaining older versions up to the given retention threshold. This method will return an empty DataFrame on successful completion.</p><pre>deltaTable<strong>.</strong>vacuum<strong>()</strong>     <em># vacuum files not required by versions more than 7 days old</em><br><br>deltaTable<strong>.</strong>vacuum<strong>(100)</strong>  <em># vacuum files not required by versions more than 100 hours old</em></pre><p>So, that’s all Folks, hope you find my article helpful.</p><p>In case you want to verify what I wrote is actually true : please find the below links for your reference.</p><ul><li><a href="https://docs.delta.io/0.4.0/api/python/index.html">Welcome to Delta Lake&#39;s Python documentation page - delta-core 0.4.0 documentation</a></li><li><a href="https://docs.databricks.com/delta/delta-update.html">Table Deletes, Updates, and Merges</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1963921e4de6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/getting-hands-dirty-in-spark-delta-lake-1963921e4de6">Getting hands dirty in Spark Delta Lake</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Delta Lake]]></title>
            <link>https://medium.com/analytics-vidhya/spark-delta-lake-d05dd480287a?source=rss-9cea112ffd4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d05dd480287a</guid>
            <category><![CDATA[acid-on-spark]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Abid Merchant]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 09:31:28 GMT</pubDate>
            <atom:updated>2019-12-24T07:32:30.437Z</atom:updated>
            <content:encoded><![CDATA[<h4>ACID on Spark along with some upgradations.</h4><p>Hey Fellas,</p><p>Hope you are doing good, today I will explain you about Delta Lake!</p><p>This is 1st part of my article in which I will explain you about issues in Apache Spark and need of Delta Lake, next article will contain the interesting part of hands on…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*vxgVZ4LubyxAW43YYH8Law.jpeg" /></figure><p>One of the <a href="https://databricks.com/sparkaisummit/north-america/2019-spark-summit-ai-keynotes">key note</a> of this year’s Spark Summit was announcing <a href="http://delta.io/">Delta Lake Open Source Project</a>. The main idea behind delta lake is bringing the ACID features back to Big Data which seemed like a long lost thing of past. Apart from Spark being robust and fast it lacked ACID qualities which seemed of little importance at start but gradually lack of it is hindrance for Spark Projects. Many Spark Big Data projects which went to production failed because of issues like:</p><ul><li>Lack of schema enforcement</li><li>No support for delta load</li><li>Corrupted data in Data Lake</li></ul><p>With Delta Lake we will be able to overcome these issues. Now, the most important aspect of Delta Lake is bringing ACID features back, but why is ACID features important and what were the drawbacks of not having it in Apache Spark?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*juHPSl-vTOMC3MpKP6Brvw.jpeg" /></figure><p>Let me get to basics a bit and tell you the issues faced by us in Apache Spark.</p><ul><li>Atomicity : It means the job should be completed fully or it should not make any effect at all. As per Spark <a href="https://spark.apache.org/docs/latest/sql-data-sources-load-save-functions.html#save-modes">documentation</a>, Save Mode is not atomic but however this feature is followed in Apache Spark through FileOutputCommiter version 1 (for Hdfs).</li><li>Consistency : In Spark, when performing an overwrite, the data will be deleted before writing the new data. This means there will be timespan where data is completely lost and an exception at that time will result in loss of data which is bit scary as we might end up with no data at all.</li><li>Isolation : It means read and write operation on same dataset should be isolated with each other. Due to lack of atomicity in write operations in Apache Spark it does not guarantee Isolation.</li><li>Durability : This feature means “Once committed is never lost”. Hdfs helps to maintain durability in Spark, but issue might happen if Spark does not commit job properly.</li></ul><p>Apart from the issues of ACID, lack of schema enforcement is also a major impediment as Spark follows schema on read and during delta loads if some column datatype mismatch happens, we will be able to write it to Data Lake without any issues, but this will result in corrupting our Data.</p><p>So, Databricks decided to put a full stop to these issues and announced Delta Lake! Delta Lake is built on top of parquet format which is most commonly used in Big Data projects.</p><p>Delta Lake brings us following features:</p><ul><li>ACID transactions on Data Lake</li><li>Schema Enforcement</li><li>Time Travel Capabilities</li></ul><p>With ACID transactions possible in Spark, we will be able to perform operations like Updation, Deletion and Merge. There was no possible way to update our existing data or Merge new data but with Delta lake all of this will be possible with only one command. Moreover, a transaction log file will be maintained.</p><p>With Schema Enforcement capability, schema on write will be followed. This means any change in datatype or schema will be caught red handed at the time of write which will stop it to go in Data Lake and corrupt our data and get us exceptions while executing our jobs which gave us Nightmare to rectify.</p><p>The best and the coolest part of Delta Lake is its Time Travel capability, which will be of utmost importance to fellow Data Scientists, because it will maintain different versions of the dataset each time we perform an operation on our dataset. So with Time Travel, overwrite or append to our Data Lake does not actually mean losing our old data in that actual form. We just have to search our dataset with the version we want and the dataset at that time will be returned to us, cool isn’t it. So, while running different dataset for a prediction model, we time travel to old datasets as well which might have given us better results.</p><p>So, this was a short overview of Databricks Delta Lake. In the next article I will show you hands on along with installation of Delta Lake in Pyspark. Till then good bye, ta ta, Vanakkam.</p><p>Click the below link for the follow up article containing code and hands on of Delta Lake.</p><p><a href="https://medium.com/@merchantabid4/getting-hands-dirty-in-spark-delta-lake-1963921e4de6">Getting hands dirty in Spark Delta Lake</a></p><p>Do checkout the video of Delta Lake Announcement at Spark Summit 2019 by Databricks.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5I5pqDsvGEc%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5I5pqDsvGEc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5I5pqDsvGEc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24d04e426feea1b23897e0741f09a9df/href">https://medium.com/media/24d04e426feea1b23897e0741f09a9df/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d05dd480287a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/spark-delta-lake-d05dd480287a">Spark Delta Lake</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Spark UDFs]]></title>
            <link>https://medium.com/analytics-vidhya/dabbling-into-spark-udfs-de52416de6bb?source=rss-9cea112ffd4e------2</link>
            <guid isPermaLink="false">https://medium.com/p/de52416de6bb</guid>
            <category><![CDATA[udf]]></category>
            <category><![CDATA[spark-dataframe]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[dataframes]]></category>
            <dc:creator><![CDATA[Abid Merchant]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 19:23:28 GMT</pubDate>
            <atom:updated>2019-12-24T07:29:17.922Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Spark User Defined functions with example</h4><p>Hey Fellas,</p><p>Many of us would have faced serious issues while performing lambda functions in spark Dataframes and in RDDs. Even though lambda functions are very much easy and useful at the sametime, doing some tasks using lambda functions is bit cumbersome sometimes.</p><p>So, if you all are bit stuck when applying lambda functions, let me introduce you all to the concept of UDFs(User Defined Functions) in Spark, it does something like…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mPpNrH_b3DEd0HiljDqMkw.png" /></figure><p>Correct, spark UDFs are basically passing a python function to be used in Spark Dataframes or RDDs(bit orthodox I reckon), interesting isn’t it!</p><p>Let me help you explore more in this concept by an example. I have dataset which consists occupational data as shown in figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*grvDJpGeiKYlijZBDwmeuQ.png" /></figure><p>So, I want to get count of occupations in a particular age group of range 10, i.e. 10–20, 20–30,… So to get the age group we will be using a Spark UDF function.</p><p>Let me start by reading the dataset…</p><pre>userDF = spark.read.option(“header”, “true”) \<br> .option(“delimiter”, “;”) \<br> .option(“inferSchema”, “true”) \<br> .csv(“user.csv”) \<br> .select(‘userid’,’age’,’gender’,’occupation’)</pre><p>So, now we have the dataset, lets quickly make a python function using if-else conditional chain to divide ages.</p><pre>def age_group(age):<br> if age &lt; 10:<br> return ‘0–10’<br> elif age &lt; 20:<br> return ‘10–20’<br> elif age &lt; 30:<br> return ‘20–30’<br> elif age &lt; 40:<br> return ‘30–40’<br> elif age &lt; 50:<br> return ‘40–50’<br> elif age &lt; 60:<br> return ‘50–60’<br> elif age &lt; 70:<br> return ‘60–70’<br> elif age &lt; 80:<br> return ‘70–80’<br> else:<br> return ‘80+’</pre><p>Now that our python function is ready, we will make a spark UDF function and pass the python function in it.</p><pre>from pyspark.sql.functions import udf<br>agegroup_udf = udf(lambda z: age_group(z))<br>userDFAgeGroup = userDF.withColumn(‘AgeGroup’,agegroup_udf(F.col(‘age’)))</pre><p>So, basically we will get <em>agegroup_udf</em> function which now can be passed in Dataframe to perform operations on its columns. So, I have applied the UDF function on age column to get AgeGroup (so obvious!).</p><p>Lets check our newly born dataframe’s health</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*_HhdrQTJ_-Z4F7uwBICWHw.png" /></figure><p>Hallelujah, we got the AgeGroup column by applying UDF, wasn’t it simple? Now lets aggregate the data based on our newly added column and get the final result.</p><pre>userDF_count = userDFAgeGroup.groupBy(F.col(‘AgeGroup’),F.col(‘occupation’)) \<br> .agg(F.count((F.col(‘occupation’))).alias(‘count’))</pre><p>Let me show you the end result I got.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*fOD44eOC3hKsclohW9JLIw.png" /></figure><p>Phew, finally we reached our landmark and got the count per each age group and occupation. The uses and benefits of UDFs are endless as this example just opening a small window in the world of UDFs.</p><p>Hope you liked my article, if you want to checkout full code checkout my github link below:</p><p><a href="https://github.com/AbidMerchant/Pyspark_udf_partition">https://github.com/AbidMerchant/Pyspark_udf_partition</a></p><p>That’s all Folks! Ta Ta</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de52416de6bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/dabbling-into-spark-udfs-de52416de6bb">Exploring Spark UDFs</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>