<?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 Priya Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Priya Chauhan on Medium]]></description>
        <link>https://medium.com/@priya.chauhangfi?source=rss-c8fbc303b39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PlxPuA7kiqaK7vDRn_VW_g.jpeg</url>
            <title>Stories by Priya Chauhan on Medium</title>
            <link>https://medium.com/@priya.chauhangfi?source=rss-c8fbc303b39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:00:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@priya.chauhangfi/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[Solving Tricky DP-203 Questions : Part 1]]></title>
            <link>https://medium.com/@priya.chauhangfi/solving-tricky-dp-203-questions-part-1-420d8e083afa?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/420d8e083afa</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 14:14:05 GMT</pubDate>
            <atom:updated>2024-08-22T14:14:05.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving Tricky DP-203 Questions : Part 1</h3><p>You have an Azure subscription linked to an Azure Active Directory (Azure AD) tenant that contains a service principal named ServicePrincipal1. The subscription contains an Azure Data Lake Storage account named adls1. Adls1 contains a folder named Folder2 that has a URI of <a href="https://adls1.dfs.core.windows.net/">https://adls1.dfs.core.windows.net/</a> container1/Folder1/Folder2/.<br>ServicePrincipal1 has the access control list (ACL) permissions shown in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*lYUp76_6n7JJyNwy.png" /></figure><p>You need to ensure that ServicePrincipal1 can perform the following actions:<br>✑ Traverse child items that are created in Folder2.<br>✑ Read files that are created in Folder2.<br>The solution must use the principle of least privilege.<br>Which two permissions should you grant to ServicePrincipal1 for Folder2? Each correct answer presents part of the solution.<br>NOTE: Each correct selection is worth one point.</p><ul><li>A. Access Read</li><li>B. Access Write</li><li>C. Access Execute</li><li>D. Default Read</li><li>E. Default Write</li><li>F. Default Execute</li></ul><p>Let’s implement this in Azure portal</p><h3><strong>Step 1 : Create a Security Principal</strong></h3><p>Creating a security principal is equivalent to creating an app in Microsoft Entra ID(also called Azure Active Directory)</p><p>Search for Microsoft Entra ID in the azure portal search bar and click add</p><p>You will see app registration option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wiascl4t1bbI27etdnQoLg.png" /></figure><p>Provide a name, select the account type, and click on register</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVREzmMWit3GpYN0qdgdDg.png" /></figure><p>Now , you need to create the client secret for your registered app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPY13qHg22Sj_O_AY54LYQ.png" /></figure><p>Click on certificate &amp; secret section and then click on New Client secret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H443RPSdfhpNaxuWQDrLxQ.png" /></figure><p>Add description and expiry date</p><h3>Step 2: Assign the Service Principal to the Data Lake Storage Account</h3><ol><li><strong>Navigate to the Azure Data Lake gen2 account(if not then create it by via storage account azure resource</strong></li><li><strong>Assign the Storage Blob Data Contributor Role</strong>:</li></ol><p>Go to <strong>Access control (IAM)</strong> on the left panel.</p><ul><li>Click on <strong>Add</strong> &gt; <strong>Add role assignment</strong>.</li><li>In the <strong>Role</strong> drop-down, select <strong>Storage Blob Data Contributor</strong>.</li><li>In the <strong>Assign access to</strong> drop-down, select <strong>Service principal that we created above</strong>.</li><li>Search for ServicePrincipal and select it.</li><li>Click <strong>Save</strong> to apply the role assignment.</li></ul><h3>Step 3: Set Access Permissions on Folder Level Using ACLs</h3><ol><li><strong>Navigate to the Data Lake Storage Hierarchy</strong>:</li></ol><p>In the storage account (adlsgen2certprepdev), go to <strong>Containers</strong> and select file(file is container name ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaDAhYBEAaWoE135wic7kw.png" /></figure><ul><li>Now as per question , let’s grant access via ACLs(Access Control Lists)</li><li>For container file, right click and select manage ACL and grant Execute permission and hit save.</li><li>For folder1 , grant execute permission via Manage ACL.</li><li>Navigate through the folder structure to reach Folder1 &gt; Folder2.</li></ul><ol><li><strong>Modify Access Control Lists (ACLs)</strong>:</li></ol><p>In the <strong>Folder2</strong> level, click on the three dots next to the folder name and select <strong>Manage ACL</strong>.</p><ul><li>Under <strong>Access</strong>, click <strong>Add</strong> and search for ServicePrincipal.</li><li>Set the permissions to <strong>Read</strong>(as needed in question).</li><li>Click <strong>Save</strong>.</li></ul><p>Its time to test it, whether we can traverse it or not?</p><p>Switch to Azure Cloud shell and run below command(edit your client secret and service principal creds)</p><pre>az login --service-principal -u &lt;CLIENT_ID&gt; -p &lt;CLIENT_SECRET_value&gt; --tenant &lt;TENANT_ID&gt;<br><br>az storage blob list \<br>  --account-name adlsgen2certprep \<br>  --container-name file \<br>  --prefix &quot;folder1/folder2/&quot; \<br>  --auth-mode login</pre><p>You will get below output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*aOahvFgBwQOkDP0Eoe6nlg.png" /></figure><p>This confirms that we can traverse with default Read access, option D is confirmed</p><pre>az storage blob download \<br>  --account-name adlsgen2certprepdev \<br>  --container-name file \<br>  --name &quot;folder1/folder2/file1.csv&quot; \<br>  --file ./download_file_path \<br>  --auth-mode login</pre><p>Run above command to check if you can read or not,</p><p>We can’t read , so give execute permission as well to the security principal and after hitting the above command again, you will be able to read the content of the file .</p><p>This confirmed Option C Access Execute</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420d8e083afa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 15 Questions of Spark ranging from service based companies to Product based companies.]]></title>
            <link>https://medium.com/@priya.chauhangfi/top-15-questions-of-spark-ranging-from-service-based-companies-to-product-based-companies-9a6e987f4393?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a6e987f4393</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 17:00:03 GMT</pubDate>
            <atom:updated>2023-07-24T17:00:03.591Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Top 15 Questions of Spark ranging from service based companies to Product based companies.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvAqCyH7DF0sLIN1Vo3MOQ.png" /></figure><h3>Day 6 on Cracking Data Engineering Interview at any company.</h3><p>Note : This series will be continued till Day 30 and it is not to target any specific company but to crack any company because at the end we should know how to get the work done once we are onboarded in the company with our technical skills</p><p>You can watch my previous story to know about spark, if you are new to this technology : <a href="https://medium.com/@priya.chauhangfi/day-5-on-cracking-data-engineering-interview-at-any-company-91e6f63ea615">https://medium.com/@priya.chauhangfi/day-5-on-cracking-data-engineering-interview-at-any-company-91e6f63ea615</a></p><p>PySpark in a nutshell : When you are interacting with spark engine by using python API , its called pyspark.</p><p><strong>Q1. What is Spark, explain its architecture and working (Asked in Service based companies)</strong></p><p>Best Answer : Spark is a unified analytics engine for large-scale data processing.(Big data processing)</p><ul><li>It provides high-level APIs in Java, Scala, Python and R, and an optimized engine that supports general execution graphs.</li><li><strong>Architecture</strong> : Refer this in-depth article <a href="https://blog.knoldus.com/understanding-the-apache-spark-architecture/">https://blog.knoldus.com/understanding-the-apache-spark-architecture/</a></li><li><strong>Working</strong> : <a href="https://blog.knoldus.com/understanding-the-working-of-spark-driver-and-executor/">https://blog.knoldus.com/understanding-the-working-of-spark-driver-and-executor/</a></li></ul><p><strong>Q2 . Find out min, max and cumulative salary in a dataset with emp_name, dept_name and salary as columns</strong></p><p><strong>some interviewer will specifically ask you to Create a sparksession, dataframe , define schema and then write the logic.</strong></p><p><strong>(Asked in Service based companies)</strong></p><p>Best Answer :</p><pre>#import relevant libraries<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType,FloatType<br>from pyspark.sql.window import Window<br>from pyspark.sql.functions import rank,col,min,max,row_number,max,asc,desc,when,count,sum<br>#Let&#39;s create Sparksession First<br><br><br>spark=SparkSession.builder.master(&quot;local[1]&quot;).appName(&quot;Prep&quot;).getOrCreate()<br><br>data= [(&quot;James&quot;, &quot;Sales&quot;, 2000),<br>(&quot;sofy&quot;, &quot;Sales&quot;, 3000),<br>(&quot;Laren&quot;, &quot;Sales&quot;, 4000),<br>(&quot;Kiku&quot;, &quot;Sales&quot;, 5000),<br>(&quot;Sam&quot;, &quot;Finance&quot;, 6000),<br>(&quot;Samuel&quot;, &quot;Finance&quot;, 7000),<br>(&quot;Yash&quot;, &quot;Finance&quot;, 8000),<br>(&quot;Rabin&quot;, &quot;Finance&quot;, 9000),<br>(&quot;Lukasz&quot;, &quot;Marketing&quot;, 10000),<br>(&quot;Jolly&quot;, &quot;Marketing&quot;, 11000),<br>(&quot;Mausam&quot;, &quot;Marketing&quot;, 12000),<br>(&quot;Lamba&quot;, &quot;Marketing&quot;, 13000),<br>(&quot;Jogesh&quot;, &quot;HR&quot;, 14000),<br>(&quot;Mannu&quot;, &quot;HR&quot;, 15000),<br>(&quot;Sylvia&quot;, &quot;HR&quot;, 16000),<br>(&quot;Sama&quot;, &quot;HR&quot;, 17000),<br>]<br><br>#Schema<br><br>emp_schema = StructType([StructField(&quot;name&quot;,StringType()), StructField(&quot;dept_name&quot;,StringType()),StructField(&quot;Salary&quot;, StringType())])<br><br>employees_Salary_df.show(truncate=False)<br><br>#creating window<br><br>windowval = (Window.partitionBy(&#39;dept_name&#39;).orderBy(&#39;Salary&#39;)<br>             .rowsBetween(Window.unboundedPreceding, 0))<br><br><br>#getting cumulatibve salary<br><br>cum_sum_df = employees_Salary_df.withColumn(&quot;rank_desc&quot;,row_number().over(windowspec)).withColumn(&quot;rank_asc&quot;,row_number().over(windowspec1)).withColumn(&#39;cum_sum&#39;,sum(col(&quot;Salary&quot;).cast(IntegerType())).over(windowval))<br><br><br>#getting min and max salary<br>employees_Salary_df.groupBy(&quot;dept_name&quot;).agg(max(&quot;MaxSal&quot;).alias(&quot;Max_Sal&quot;),max(&quot;MinSal&quot;).alias(&quot;Min_Sal&quot;))<br>employees_Salary_df.show(truncate=False)</pre><p>Try to run this in databricks community edition or any ide of your choice to view the results.</p><p>Don’t worry if you encountered an error, use stackoverflow.</p><p><strong>Question 3 : Write a pyspark code to swap the gender having gender and name as dataset columns(Asked in service based companies)</strong></p><p>Answer : try it out by yourself</p><p><strong>Question 4 : Write a pyspark code to handle exceptins while reading and writing a file (Asked in service based and consulting companies)</strong></p><p>Best Way to Answer :</p><p>First you need to read about errors and exception here : <a href="https://sparkbyexamples.com/python/python-try-except-with-examples/">https://sparkbyexamples.com/python/python-try-except-with-examples/</a></p><pre>def rdf(name, type):<br>   try:<br>      df=spark.read.format(type).load(name)<br>      return df<br>   except Exception as e:<br>    if &#39;java.io.FileNotFoundException&#39; in str(e):<br>      print(&#39;File does not exists&#39;)<br>    else:<br>      print(&#39;Other error&#39;)</pre><p>This is one way, you can experiment it more to catch other possible errors, such as directory not present if we are looking a bunch of files in a dircetory.</p><p><strong>Question 4 : Write a pyspark code to generate the below output for the given input dataset(Asked in service based companies)</strong></p><pre><br>input dataset :<br><br>+------+---------+----------+-----------+---------+<br>|EmpId |Name     | Location1| Loccation2| Location3<br>+------+---------+----------+-----------+---------+<br>|1     |Gaurav   | Pune     | Bangalore| Hyderabad|<br>|2     |Risabh   | Mumbai   | Bangalore| Pune     |<br>+------+---------+----------+-----------+---------+<br><br> <br>Required Output<br><br>EmpId Name Location<br>1     Gaurav  Pune<br>1     Gaurav  Bangalore<br>1     Gaurav  Hyderabad<br>2     Risabh  Mumbai<br>2     Risabh  Pune</pre><p>Answer : try on your own(Hint : Unpivot function)</p><p><strong>Question 5 : given two datasets, What should I do to get non-matching records from the left table (Asked in Service based companies)</strong></p><pre><br>import pyspark<br>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&#39;sparkbyexamples.com&#39;).getOrCreate()<br><br>emp = [(1,&quot;Smith&quot;,-1,&quot;2018&quot;,&quot;10&quot;,&quot;M&quot;,3000), \<br>    (2,&quot;Rose&quot;,1,&quot;2010&quot;,&quot;20&quot;,&quot;M&quot;,4000), \<br>    (3,&quot;Williams&quot;,1,&quot;2010&quot;,&quot;10&quot;,&quot;M&quot;,1000), \<br>    (4,&quot;Jones&quot;,2,&quot;2005&quot;,&quot;10&quot;,&quot;F&quot;,2000), \<br>    (5,&quot;Brown&quot;,2,&quot;2010&quot;,&quot;40&quot;,&quot;&quot;,-1), \<br>      (6,&quot;Brown&quot;,2,&quot;2010&quot;,&quot;50&quot;,&quot;&quot;,-1) \<br>  ]<br>empColumns = [&quot;emp_id&quot;,&quot;name&quot;,&quot;superior_emp_id&quot;,&quot;year_joined&quot;, \<br>       &quot;emp_dept_id&quot;,&quot;gender&quot;,&quot;salary&quot;]<br><br>empDF = spark.createDataFrame(data=emp, schema = empColumns)<br>empDF.printSchema()<br>empDF.show(truncate=False)<br><br>dept = [(&quot;Finance&quot;,10), \<br>    (&quot;Marketing&quot;,20), \<br>    (&quot;Sales&quot;,30), \<br>    (&quot;IT&quot;,40) \<br>  ]<br>deptColumns = [&quot;dept_name&quot;,&quot;dept_id&quot;]<br>deptDF = spark.createDataFrame(data=dept, schema = deptColumns)<br>deptDF.printSchema()<br>deptDF.show(truncate=False)</pre><p>use the above code to get the datasets(dataset taken from sparkbyexamples)</p><p>Answer : perform left-semi join in your IDE</p><p><strong>Question 6 : What is broadcast variables, broadcast join (write the code for broadcast join) (Asked in service based and consulting companies)</strong></p><p>Answer : read about broadcast join here : <a href="https://sparkbyexamples.com/pyspark/pyspark-broadcast-join-with-example/">https://sparkbyexamples.com/pyspark/pyspark-broadcast-join-with-example/</a></p><p>Also read and practice about broadcast threshold amount</p><p><strong>Question 7 : Have you ever encountered with OOM Error if yes what are their causes and how did you resolve it (asked in consulting firms and service companies)</strong></p><p>Answer : I followed this article to answer this :</p><p><a href="https://medium.com/swlh/spark-oom-error-closeup-462c7a01709d">Spark OOM Error — Closeup</a></p><p><strong>Question 8 : What are spark internal join strategies (Asked in consulting and service companies)</strong></p><p>Answer : Even if the interviewer doesn’t ask, explain this in brief</p><p>I followed this article to answer this : <a href="https://blog.knoldus.com/joins-in-apache-spark/">https://blog.knoldus.com/joins-in-apache-spark/</a></p><p>it has all the join strategies explained pictorially, you can view it while practicing in databricks community edition.</p><p>Question 9 : for the below data</p><pre>data = [(1234,&quot;Coke&quot;,23,&quot;2023–06–13&quot;),(1234,&quot;Coke&quot;,12,&quot;2023–06–12&quot;),<br>(1234,&quot;CokeOne&quot;,20,&quot;2023–06–13&quot;),(1234,&quot;CokeOne&quot;,11,&quot;2023–06–10&quot;),<br>(1224,&quot;Sprite&quot;,21,&quot;2023–06–13&quot;),(1224,&quot;Sprite&quot;,123,&quot;2023–05–13&quot;),(1224,&quot;Coke&quot;,53,&quot;2023–04–13&quot;)]<br><br>columns = [&quot;Store_id&quot;,&quot;Product&quot;,&quot;Quantity&quot;,&quot;Order_date&quot;]</pre><p>find total quantity at store and prod level. Also find the days whe product was not ordered</p><p>This question was asked in consulting companies</p><p>Answer : Please try it on your own</p><p><strong>Question 10 : What are the optimizations techniques you have worked with. Explain in brief (Asked in service, consulting and product based companies)</strong></p><p>Answer : <a href="https://sparkbyexamples.com/spark/spark-performance-tuning/">https://sparkbyexamples.com/spark/spark-performance-tuning/</a></p><p>Even though , the techniques depends on your project, but knowing all possible techniques can keep you forward.</p><p><strong>Question 12 : what are stages and tasks in spark and how the number of stages are defined(Asked in service and consulting companies)</strong></p><p>Answer : <a href="https://blog.knoldus.com/understanding-spark-application-concepts/#:~:text=In%20Spark%2C%20a%20Task%20is,a%20single%20partition%20of%20data">https://blog.knoldus.com/understanding-spark-application-concepts/#:~:text=In%20Spark%2C%20a%20Task%20is,a%20single%20partition%20of%20data</a>.</p><p>Best way to asnwer number of stages and task : When you will execute your results in question 2, see the spark execution plan, dag graph .</p><p>and try to articulate your answer accordingly.</p><p>for example, if I do x and y transformation on abc dataset, and if I click on the execution plan, I see these many number of stages against every transformation</p><p><strong>Question 13 : Explain predicate pushdown in spark(Asked in Big4)</strong></p><p>Answer : <a href="https://medium.com/@deepa.account/apache-spark-and-predicate-pushdown-f6a41d53bef5">https://medium.com/@deepa.account/apache-spark-and-predicate-pushdown-f6a41d53bef5</a></p><p>Question 14 : How to decide number of executors and memory in spark job ?(Asked in Service based companies)</p><p>Answer : Watch this 6 min video</p><p><a href="https://www.youtube.com/watch?v=WCO_r_lgrJU">https://www.youtube.com/watch?v=WCO_r_lgrJU</a></p><p>Question 15 : How driver and executors work together in spark (Asked in consulting companies)</p><p>Answer : Read about executors and driver responsibilties</p><p><a href="https://blog.knoldus.com/understanding-the-working-of-spark-driver-and-executor/">https://blog.knoldus.com/understanding-the-working-of-spark-driver-and-executor/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a6e987f4393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[+ — — — + — — — — -+ — — — + — — — — -+ — — — — + — — — -+ — — — + — — — +
 |name…]]></title>
            <link>https://medium.com/@priya.chauhangfi/name-2d92589e05b9?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d92589e05b9</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Sun, 28 May 2023 11:32:21 GMT</pubDate>
            <atom:updated>2023-05-28T16:14:50.682Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Find Maximum and Minimum Salary in each department by using PySpark</strong></p><p>SQL Reference : Ankit Bansal L&amp;T SQL Interview Problem</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7W7B0y5WsaQ%3Fstart%3D11%26feature%3Doembed%26start%3D11&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7W7B0y5WsaQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7W7B0y5WsaQ%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/b983b2af1457f77ee4e7470ff165ecb3/href">https://medium.com/media/b983b2af1457f77ee4e7470ff165ecb3/href</a></iframe><p>I am using jupyter notebook here to perform the solution</p><p>You can download anaconda and run !pip install pyspark in order to run pyspark code in jupyter notebook</p><p>Solution:</p><pre>#import relevant libraries<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType,FloatType<br>from pyspark.sql.window import Window<br>from pyspark.sql.functions import rank,col,min,max,row_number,max,asc,desc,when,count,sum<br>#Let&#39;s create Sparksession First<br><br><br>spark=SparkSession.builder.master(&quot;local[1]&quot;).appName(&quot;Prep&quot;).getOrCreate()<br><br>data= [(&quot;James&quot;, &quot;Sales&quot;, 2000),<br>(&quot;sofy&quot;, &quot;Sales&quot;, 3000),<br>(&quot;Laren&quot;, &quot;Sales&quot;, 4000),<br>(&quot;Kiku&quot;, &quot;Sales&quot;, 5000),<br>(&quot;Sam&quot;, &quot;Finance&quot;, 6000),<br>(&quot;Samuel&quot;, &quot;Finance&quot;, 7000),<br>(&quot;Yash&quot;, &quot;Finance&quot;, 8000),<br>(&quot;Rabin&quot;, &quot;Finance&quot;, 9000),<br>(&quot;Lukasz&quot;, &quot;Marketing&quot;, 10000),<br>(&quot;Jolly&quot;, &quot;Marketing&quot;, 11000),<br>(&quot;Mausam&quot;, &quot;Marketing&quot;, 12000),<br>(&quot;Lamba&quot;, &quot;Marketing&quot;, 13000),<br>(&quot;Jogesh&quot;, &quot;HR&quot;, 14000),<br>(&quot;Mannu&quot;, &quot;HR&quot;, 15000),<br>(&quot;Sylvia&quot;, &quot;HR&quot;, 16000),<br>(&quot;Sama&quot;, &quot;HR&quot;, 17000),<br>]<br><br>#Schema<br><br>emp_schema = StructType([StructField(&quot;name&quot;,StringType()), StructField(&quot;dept_name&quot;,StringType()),StructField(&quot;Salary&quot;, StringType())])<br><br>employees_Salary_df.show(truncate=False)</pre><p>It will give below result</p><pre>+------+---------+------+<br>|name  |dept_name|Salary|<br>+------+---------+------+<br>|James |Sales    |2000  |<br>|sofy  |Sales    |3000  |<br>|Laren |Sales    |4000  |<br>|Kiku  |Sales    |5000  |<br>|Sam   |Finance  |6000  |<br>|Samuel|Finance  |7000  |<br>|Yash  |Finance  |8000  |<br>|Rabin |Finance  |9000  |<br>|Lukasz|Marketing|10000 |<br>|Jolly |Marketing|11000 |<br>|Mausam|Marketing|12000 |<br>|Lamba |Marketing|13000 |<br>|Jogesh|HR       |14000 |<br>|Mannu |HR       |15000 |<br>|Sylvia|HR       |16000 |<br>|Sama  |HR       |17000 |<br>+------+---------+------+</pre><pre>#creating windows<br><br>windowspec_desc=Window.partitionBy(&quot;dept_name&quot;).orderBy(col(&quot;Salary&quot;).desc())<br>windowspec_asc=Window.partitionBy(&quot;dept_name&quot;).orderBy(col(&quot;Salary&quot;).asc())<br><br>#generating rank over specified window<br><br>rank_df = employees_Salary_df.withColumn(&quot;rank_desc&quot;,row_number().over(windowspec)).withColumn(&quot;rank_asc&quot;,row_number().over(windowspec1))<br><br>row_number_df.show(truncate=False)</pre><pre>+------+---------+------+---------+--------+-------+<br>|name  |dept_name|Salary|rank_desc|rank_asc|cum_sum|<br>+------+---------+------+---------+--------+-------+<br>|James |Sales    |2000  |4        |1       |2000   |<br>|sofy  |Sales    |3000  |3        |2       |5000   |<br>|Laren |Sales    |4000  |2        |3       |9000   |<br>|Kiku  |Sales    |5000  |1        |4       |14000  |<br>|Jogesh|HR       |14000 |4        |1       |14000  |<br>|Mannu |HR       |15000 |3        |2       |29000  |<br>|Sylvia|HR       |16000 |2        |3       |45000  |<br>|Sama  |HR       |17000 |1        |4       |62000  |<br>|Sam   |Finance  |6000  |4        |1       |6000   |<br>|Samuel|Finance  |7000  |3        |2       |13000  |<br>|Yash  |Finance  |8000  |2        |3       |21000  |<br>|Rabin |Finance  |9000  |1        |4       |30000  |<br>|Lukasz|Marketing|10000 |4        |1       |10000  |<br>|Jolly |Marketing|11000 |3        |2       |21000  |<br>|Mausam|Marketing|12000 |2        |3       |33000  |<br>|Lamba |Marketing|13000 |1        |4       |46000  |<br>+------+---------+------+---------+--------+-------+<br></pre><p>As you can see , it has generated rank departmentwise</p><pre>filtered_df = rank_df.withColumn(&quot;MaxSal&quot;,when(col(&quot;rank_desc&quot;)==1 , col(&quot;name&quot;))).withColumn(&quot;MinSal&quot;,when(col(&quot;rank_asc&quot;)==1 , col(&quot;name&quot;)))<br>filtered_df.show(truncate=False)</pre><pre>+------+---------+------+---------+--------+-------+------+------+<br>|name  |dept_name|Salary|rank_desc|rank_asc|cum_sum|MaxSal|MinSal|<br>+------+---------+------+---------+--------+-------+------+------+<br>|James |Sales    |2000  |4        |1       |2000   |null  |James |<br>|sofy  |Sales    |3000  |3        |2       |5000   |null  |null  |<br>|Laren |Sales    |4000  |2        |3       |9000   |null  |null  |<br>|Kiku  |Sales    |5000  |1        |4       |14000  |Kiku  |null  |<br>|Jogesh|HR       |14000 |4        |1       |14000  |null  |Jogesh|<br>|Mannu |HR       |15000 |3        |2       |29000  |null  |null  |<br>|Sylvia|HR       |16000 |2        |3       |45000  |null  |null  |<br>|Sama  |HR       |17000 |1        |4       |62000  |Sama  |null  |<br>|Sam   |Finance  |6000  |4        |1       |6000   |null  |Sam   |<br>|Samuel|Finance  |7000  |3        |2       |13000  |null  |null  |<br>|Yash  |Finance  |8000  |2        |3       |21000  |null  |null  |<br>|Rabin |Finance  |9000  |1        |4       |30000  |Rabin |null  |<br>|Lukasz|Marketing|10000 |4        |1       |10000  |null  |Lukasz|<br>|Jolly |Marketing|11000 |3        |2       |21000  |null  |null  |<br>|Mausam|Marketing|12000 |2        |3       |33000  |null  |null  |<br>|Lamba |Marketing|13000 |1        |4       |46000  |Lamba |null  |<br>+------+---------+------+---------+--------+-------+------+------+<br><br>Ignore the cum_sum(cumulative sum)</pre><p>Now we have to take max value from MaxSal and MinSal from filtered_df</p><pre>resultant_df.groupBy(&quot;dept_name&quot;).agg(max(&quot;MaxSal&quot;).alias(&quot;Max_Sal&quot;),max(&quot;MinSal&quot;).alias(&quot;Min_Sal&quot;))<br>resultant_df.show(truncate=False)</pre><p>After this , I felt sql will be best choice for implementing this logic</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d92589e05b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 5 on Cracking Data Engineering Interview at any company.]]></title>
            <link>https://medium.com/@priya.chauhangfi/day-5-on-cracking-data-engineering-interview-at-any-company-91e6f63ea615?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/91e6f63ea615</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 18:23:24 GMT</pubDate>
            <atom:updated>2023-03-28T18:27:23.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Note : This series will be continued till Day 30 and it is not to target any specific company but to crack any company because at the end we should know how to get the work done once we are onboarded in the company with our technical skills</p><p><strong>Learning Apache Spark</strong></p><p>What is Spark ?</p><p>But let’s understand RAM vs Storage</p><p>Question : What will be faster , searching the file on your managed desk or searching it in the messy book shelf.</p><p>Answer is desk.</p><p>Similar to this analogy , retriving data from RAM is faster because <strong>RAM sits very close to the CPU and has a very high bandwidth connection</strong>.</p><p>Now Apache spark works in similar manner, but wait, we don’t know yet what it is?</p><p>Apache spark is just a compute engine meaning it is proving the infrastructure, resources that are needed to run your job faster</p><p><strong>Spark is 100% faster then hadoop map-reduce , now why we say that.</strong></p><p>because spark processes data in memory (RAM). At the same time, Hadoop MapReduce has to persist data back to the disk after every Map or Reduce action.</p><p>People who are new to Map Reduce : It is a programming model provided by hadoop to process big data</p><p>So now , we are clear that spark is a compute engine.</p><p>Great!</p><p><strong><em>Tech fact : Spark was initially started by Matei Zaharia at UC Berkeley’s AMPLab in 2009, and open sourced in 2010 under a BSD license. In 2013, the project was donated to the Apache Software Foundation and switched its license to Apache 2.0. In February 2014, Spark became a Top-Level Apache Project.</em></strong></p><p><strong><em>The Architecture</em></strong></p><p>Consider Spark as an engine of a Bus, a special Bus whose engine configuration is done by driver only.</p><p>Now once driver starts the engine with his custom configuration , engine truns on and sound is generated until the driver moves the bus ahead and all passangers are seated.</p><p>Now pls note even if the driver starts, one important thing is necessary that is petrol/diesel in the fuel tank and if that is enough, the driver will be able to drive the bus ahead.</p><p>In this scenario, The driver is spark driver,</p><p>the moment driver starts the engine with its cutom config, spark session is initiated .</p><p>Here diesel is Resources in spark achitecture. Fuel Tank is Cluster Manager</p><p>Rotating the keys to turn the engine one is called spark submit menaing you are submitting your application to execute.</p><p>Once you do a Spark submit, a driver program is launched and this requests for resources to the cluster manager and at the same time the main program of the user function of the user processing program is initiated by the driver program.</p><p>Based on that, the execution logic is processed and parallelly Spark context is also created. Using the Spark context, the different transformations and actions are processed.</p><p>Now what are transformations ?</p><p>Getting wheat flour from wheat is one transformation in life</p><p>and getting goood quality and needful business data out of raw data is another transformation in life.</p><p>transformation can be filtering some IDs with duplicate names</p><p>or it can be running a when and otherwise condition similar to sql.</p><p>so we are actually moulding the data.</p><p><strong>Now what is action ? Spark is very Lazy, until we ask him to show the results, it won’t execute the task for us.</strong></p><p>Meaning we have said to filter the even ids out of million ids.</p><p>at this time, it won’t filter , unless we are writing a show command to view the even ids.</p><p>So, till the time the action is not encountered, all the transformations will go into the Spark context in the form of DAG that will create RDD lineage.</p><p>Now what is Dag ? Directed Acyclic Graph</p><p><strong>what is RDD : Resilient Distributed Dataset</strong></p><p>Immutable distributed collection of elements of your data, partitioned across nodes in your cluster that can be operated in parallel with transformations and actions.</p><p>Once the action is called job is created. Job is the collection of different task stages.</p><p>Once these tasks are created, they are launched by the cluster manager on the worker nodes and this is done with the help of a class called task scheduler.</p><p>The conversion of RDD lineage into tasks is done by the DAG scheduler. Here DAG is created based on the different transformations in the program and once the action is called these are split into different stages of tasks and submitted to the task scheduler as tasks become ready.</p><p>Then these are launched on the different executors in the worker node through the cluster manager. The entire resource allocation and the tracking of the jobs and tasks are performed by the cluster manager.</p><p>As soon as you do a Spark submit, your user program and other configuration mentioned are copied onto all the available nodes in the cluster. So that the program becomes the local read on all the worker nodes. Hence, the parallel executors running on the different worker nodes do not have to do any kind of network routing.</p><p>This is how the<br> entire execution of the Spark job happens.</p><p>Join me on upcoming webinar on Apache Spark</p><p><a href="https://topmate.io/priya_chauhan/210580">https://topmate.io/priya_chauhan/210580</a></p><p>Hope it helped, See you on Day 6!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91e6f63ea615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 4 on Cracking Data Engineering Interview at any company.]]></title>
            <link>https://medium.com/@priya.chauhangfi/day-4-on-cracking-data-engineering-interview-at-any-company-357a9642f4e4?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/357a9642f4e4</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 10:32:17 GMT</pubDate>
            <atom:updated>2023-03-25T10:39:54.572Z</atom:updated>
            <content:encoded><![CDATA[<p>Note : This series will be continued till Day 30 and it is not to target any specific company but to crack any company because at the end we should know how to get the work done once we are onboarded in the company with our technical skills</p><p>Learning Functional Programming and Practicing some questions related to it.</p><p><strong>Functional Prgramming in Python</strong></p><p>Remember Class 11th NCERT textbook defination of function</p><p>A relation f from a set A to a set B is said to be function if every element of set A has one and only one image in set B. In other words, a function f is a relation such that no two pairs in the relation has the same first element.</p><p>The Modulus function is defined as :</p><p>The real function f : R → R defined by</p><p>f (x) = |x| = x, x≥0</p><p>-x,x &lt; 0 for all x belongs to R</p><p>Domain of f = R, Range of f = R+ ∪ {0}</p><p>so we are defining here the type of input and the kind of possible outputs that we can expect from the function</p><p><strong><em>Similarly, in functional programming, a function is a pure computation that takes one or more inputs and returns a single output without any side effects. This makes functional programming ideal for solving mathematical problems and expressing mathematical concepts in code.</em></strong></p><p>What are its key features :</p><ol><li><strong>Pure Functions : Everytime you call the function, it will do the same thing, the behaviour of the function will not change.</strong></li></ol><p>Global state and arguments is not changed.</p><p>If we pass mutable parameters to pure function , it won’t modify the function output at all</p><pre>def pure_func(List):<br>      <br>    list1 = []<br>      <br>    for i in List:<br>        list1.append(i+2)<br>          <br>    return list1<br>      <br>Original_List = [1, 2, 3, 4]<br>Modified_List = pure_func(Original_List)<br>  <br>print(&quot;Original List:&quot;, Original_List)<br>print(&quot;Modified List:&quot;, Modified_List)</pre><h3>2. Functions as first class objects in python:</h3><p>It means just as we are passing the numbers in a functin, we can also pass functions, in the below example, we are passing list of numbers which are strings and passing int function as an parameter to map function</p><pre>print(list(map(int, [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;])))<br><br>output will be [1,2,3]</pre><p><strong><em>Tech fact : Functional Programming is based on Lambda calculus of Mathematics .</em></strong></p><p>Now what is lambda calculus : it’s a way of describing how functions work, and how we can use them to create more complex functions.</p><p>3. <strong>Recursion</strong> :It involves a function calling itself repeatedly until it reaches a specific condition or “base case.” It’s a way of solving problems by breaking them down into smaller sub-problems, and then using those solutions to solve the original problem.</p><p>in below example, the base case is when n is equal to zero. If n is not 0, the function calls itself with the parameter n-1.</p><pre>def factorial(n):<br>    if n == 0:<br>        return 1<br>    else:<br>        return n * factorial(n-1)</pre><p>Let’s discuss some built-in Higher Order Function in Python:</p><p>A higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. This means that higher-order functions treat functions as first-class objects, just like any other data type such as integers, strings, or lists.</p><p>In python , map, filter, lambda ,reduce,are some inbuilt higher order functions.</p><p><strong>map()</strong> function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)</p><p><strong>Syntax : Note that an iterable is something through which we can traverse , it can be a list, string or any sequence</strong></p><p>for ex : number 1 is not an iterator as its primitive data type not a sequence, so understand when you get an error like int data type is not iterable</p><pre>map(fun, iter)</pre><p><strong>filter():</strong> The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.</p><blockquote><strong>Syntax:</strong> filter(function, sequence)</blockquote><p><strong>Lambda functions: </strong>anonymous function i.e , a function without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.</p><p><strong>Syntax:</strong></p><pre>lambda arguments: expression<br>ex : <br>func1 = lambda x:x*2<br>print(func1(2))<br></pre><blockquote>I hope its clear now, what is functional programming. Let;s practice some questions .</blockquote><p>Q1 : Write a function to flatten a nested list using recursion in Python.</p><p>Note : Flattening means converting a multidimensional list into one-D list.</p><pre>def flatten(L):<br>    if len(L) == 1:<br>            if type(L[0]) == list:<br>                    #print(L[0],&#39;1st&#39;)<br>                    result = flatten(L[0])<br>            else:<br>                    result = L<br>    elif type(L[0]) == list:<br>            #print(L[0],L[1:],&#39;second&#39;)<br>            result = flatten(L[0]) + flatten(L[1:])<br>            <br>    else:<br>            result = [L[0]] + flatten(L[1:])<br>    return result<br>    <br>print(flatten([[1],[1,2],[1,2,3]]))</pre><p>Q2 : Write a Python program that takes a list of strings as input and returns a new list of strings where each string is reversed and then sorted alphabetically, using the map() and sorted() functions and a lambda function.</p><pre>def func(str_list):<br>    reversed=list(map(lambda x : &quot;&quot;.join(sorted(x[::-1])),str_list))<br><br>    return reversed<br><br>print(func([&#39;salt&#39;,&#39;pet&#39;]))   </pre><p>Q3. Write a Python program that takes a list of integers as input and returns a new list of integers where each integer is the product of all the integers in the original list except for the integer at that index, using the reduce() and map() functions</p><pre>import functools<br><br>def func(int_list):<br>    prod=functools.reduce(lambda num1,num2:(num1*num2) ,int_list)<br>    res=list(map(lambda num:prod/num,int_list))<br>    return res<br><br>print(func([1,2,3,4,5]))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=357a9642f4e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 3 on Cracking Data Engineering Interview at any company.]]></title>
            <link>https://medium.com/@priya.chauhangfi/day-3-on-cracking-data-engineering-interview-at-any-company-7b938a8641?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b938a8641</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 17:58:04 GMT</pubDate>
            <atom:updated>2023-03-24T17:58:04.191Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Day 3 on Cracking Data Engineering Interview at any company.</strong></p><p>Note : This series will be continued till Day 30 and it is not to target any specific company but to crack any company because at the end we should know how to get the work done once we are onboarded in the company with our technical skills.</p><p>Pre-requisite : Gear up yourself and open an online sql compiler</p><p>Practicing Questions related to Sql Window Functions</p><p>In this post, I will be using postgres db and sqliteonline.com as an editor</p><p>Q1 : Write a sql query to report the student who took atleast one exam and who didn’t score neither high score nor the low score.</p><p>Note : don’t return student who have never taken the exam</p><p>DDLs</p><pre>create table student(<br>student_id int,<br>student_name varchar(100)<br>)<br>--exam table<br>create table exam(<br>exam_id int,<br>student_id int,<br>score int<br>)<br><br>insert into student(student_id,student_name)<br>values(1,&#39;George&#39;),<br>(2,&#39;Jade&#39;),<br>(3,&#39;Stella&#39;),<br>(4,&#39;Jonathan&#39;),<br>(5,&#39;Will&#39;)<br><br>insert into exam(exam_id,student_id,score)<br>values(10,1,70),<br>(10,2,80),<br>(10,3,90),<br>(20,1,80),<br>(30,1,70),<br>(30,3,80),<br>(30,4,90),<br>(40,1,60),<br>(40,2,70),<br>(40,4,80)</pre><p>My attempts:</p><p>With using over clause</p><pre>with cte  as (<br>select s.student_id, s.student_name,e.score,e.exam_id<br>from student s right join exam e on s.student_id = e.student_id)<br>             ,cte_2 as (<br>select * ,max(score) over(partition by exam_id) as high , <br>  min(score) over(partition by exam_id) as low from cte)<br><br>select student_id, student_name,score from cte_2<br>where score != high and score != low<br>order by student_id asc</pre><p>Without using over clause</p><pre>with cte as (<br>select exam_id ,max(score) as high , min(score) as low from exam group by exam_id order by exam_id asc)<br>,cte_2 as (<br>select s.student_id, s.student_name,e.score,e.exam_id<br>from student s right join exam e on s.student_id = e.student_id<br>)<br>select cte_2.student_name, cte_2.student_id ,cte_2.score from cte_2 <br>inner join cte on cte.exam_id = cte_2.exam_id<br>where cte_2.score not in (cte.high,cte.low)<br>order by cte_2.student_id asc</pre><p>If you find challenging to understand over clause, usage of partition by clause, window functions, then please read my story titled :</p><p><strong>Deep Dive into Window Functions</strong></p><p><a href="https://medium.com/@priya.chauhangfi/deep-dive-into-window-functions-67037731dcc1">Deep Dive into Window Functions</a></p><p>Question 2 : in next post. Stay Tuned</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b938a8641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Window Functions]]></title>
            <link>https://medium.com/@priya.chauhangfi/deep-dive-into-window-functions-67037731dcc1?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/67037731dcc1</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 11:48:57 GMT</pubDate>
            <atom:updated>2023-03-24T11:48:57.105Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Deep Dive into Window Functions</strong></p><p>What is Window :</p><ol><li>A window is a group of related rows.</li><li>For example, a window might be defined based on timestamps, with all rows in the same month grouped in the same window Or a window might be defined based on location, with all rows from a particular city grouped in the same window.</li></ol><p>Let’s create a table called mo_count(mo stands for month)</p><p>Note : All examples are performed in Snowflake.</p><p>Here attaching the create and insert queries:</p><pre>create table mo_count(entered_rows number, t_stmp timestamp);<br><br>insert into mo_count values(2, &#39;2022–12–04 17:24:00.123&#39;);<br>insert into mo_count values(2, &#39;2022–11–04 15:24:00.123&#39;);<br>insert into mo_count values(3, &#39;2022–11–04 13:24:00.123&#39;);<br>insert into mo_count values(4, &#39;2022–10–04 14:24:00.123&#39;);<br>insert into mo_count values(5, &#39;2022–10–04 16:24:00.123&#39;);<br>insert into mo_count values(6, &#39;2022–12–04 17:25:00.123&#39;);<br>insert into mo_count values(7, &#39;2022–12–04 17:26:00.123&#39;);</pre><p>Let’s try out some queries:</p><p>The basic :</p><pre>select * from mo_count;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9tfQV7tbUqQhGXo1H_pCA.png" /></figure><p>This table includes the number of records inserted at a particular timestamp.</p><p>Let’s experiment on window functions!</p><p>but firstly, what are they ?</p><p><strong>A window function is any function that operates over a window of rows.</strong></p><p>A window function is generally passed two parameters:</p><ul><li>A row. More precisely, a window function is passed 0 or more expressions. In almost all cases, at least one of those expressions references a column in that row. (Most window functions require at least one column or expression, but a few window functions, such as some rank-related functions, do not required an explicit column or expression.)</li><li>A window of related rows that includes that row. The window can be the entire table, or a subset of the rows in the table.</li><li>Window functions behave differently; although the current row is passed as an argument the normal way, the window is passed through a separate clause, called an OVER clause</li></ul><p>Do you think count is a window function ?</p><p>(Think…..)</p><p>..</p><p>..</p><p>..</p><p>Yes, it is a Aggregate window function.</p><p>Basically, Window function are of two types :</p><ol><li><strong>Aggregate window functions </strong>: these types of window functions calculate the aggregated values of a group of rows from the table.</li></ol><p>This includes SUM, COUNT, MIN, MAX, AVG, etc</p><p>2. <strong>Analytical Window Functions</strong> — These types of functions are used to calculate some window based on the current row and then calculate the results based on that window of records.</p><p>This includes : RANK, DENSE_RANK, CUME_DIST, RANK, LEAD, LAG, etc.</p><p>Let’s experiment on count window function on our table, before that let’s insert some null values :</p><pre>insert into mo_count values(null, &#39;2022–12–04 17:26:00.123&#39;);<br>insert into mo_count values(5, null);</pre><pre>select count(*) from mo_count;<br>select count(entered_rows, t_stmp) from mo_count;</pre><p>Observe the difference on running above queries.</p><p>The first returns 9, while the next returns 7</p><p>Reason for behaviour of second query : If the arguments passed into count function are two or more, then it will exclude the rows having null values in any of the column.</p><p>Similarly, sum and avg functions also functions like this.</p><p>Now let’s understand <strong>Window Frame</strong></p><p>A <strong>window frame</strong> is a sub-group of the rows in a window. Creating subsets allows us to compute values over just that specified sub-group of rows. Window frames are specified as an additional sub clause in the order by sub clause of the over clause.</p><p><strong>Types of Window Frames :</strong></p><p><strong>Cumulative : </strong>Enables computing rolling values from the beginning of the window to the current row or from the current row to the end of the window.</p><pre>cumulativeFrame ::=<br>    {<br>       { ROWS | RANGE } BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW<br>     | { ROWS | RANGE } BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING<br>    }</pre><p>ROWS : This mode will inform the database to treat every row as individual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JviiNs9m_CIc5cK6pohLA.png" /></figure><p>In the Rows mode <strong><em>frame_start</em></strong> and <strong><em>frame_end</em></strong> allow us to specify which rows the window frame starts and ends with. They accept the following values:</p><ul><li>Unbounded Preceding : (possible only in <strong><em>frame_start</em></strong>) start with the first row of the partition</li><li>Offset Preceding : start/end with a given number of rows before the current row</li><li>CURRENT ROW - start/end with the current row</li><li>offset FOLLOWING - start/end with a given number of rows after the current row</li><li>UNBOUNDED FOLLOWING - (possible only as a <strong><em>frame_end</em></strong>) end with the last row of the partition</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*7lWBEi71BaanOi1xyMrktA.png" /></figure><p><strong>Sliding : </strong>Enables computing rolling values between any two rows that is inclusive in the window, relative to the current row.</p><p>Syntax for using Window Functions :</p><pre>&lt;function&gt; ( &lt;arguments&gt; ) OVER ( [ PARTITION BY &lt;expr1&gt; ] ORDER BY &lt;expr2&gt; [ cumulativeFrame | slidingFrame ] )</pre><p>The <strong>ORDER BY</strong> subclause orders rows within the window.</p><p>This is different from ordering the output of a query. A query might have one ORDER BY clause that controls the order of rows within a window, and a separate ORDER BY clause, outside the OVER clause, that controls the output order of the entire query.</p><p>Although the ORDER BY clause is optional for some window functions, it is required for others. For example, window frame functions and rank-related functions require that the data be in a meaningful order, and therefore require an ORDER BY sub-clause.</p><p>Let’s understand these window frames by trying out 3 different queries:</p><p>Query 1: get the count of rows by month</p><pre>select entered_rows,t_stmp, count(*) over(partition by month(t_stmp))<br> as count_star from mo_count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZYJ2WQThw3EN0xIlc7LSg.png" /></figure><p>The diagram below represents the whole operation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSf415cNb_zAslj9CuSjHQ.png" /></figure><p>Let’s understand the query execution</p><p>after grouping of data in 3 different window frames , count(*) is being performed over all 3 subsets , for example , for number of rows for december month , i.e. window 1 is 3.</p><p>so wherever the month is December in t-stmp column, the output will be 3</p><p>Let’s try another query :</p><p>Get the count of entered rows by month</p><pre>select entered_rows,t_stmp, count(entered_rows) over(partition by month(t_stmp)) as count_star from mo_count</pre><p>Here the internal plan will look like below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CVeTOOdLyyE0IQ7p3zKDQ.png" /></figure><p>This query plan is same as above, but nulls are excluded here.</p><p>Similarly , if we are performing the sum(entered_rows) by Month , the results will be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*3nU3obKga7HoZ45ZQhECfA.png" /></figure><p>even the null timestamp value has been summed up and included in results.</p><p>Hope this is clear now!.</p><p>Let’s move forward, The above query is not making much sense , we have duplicate values in entered_rows_sum_by_month even though ,timestamps are different , this is because we have partitioned the data by month not by timestamp.</p><p>So the more efficient query will be something like below.</p><pre>SELECT distinct<br>monthname(T_STMP), <br> sum(ENTERED_ROWS) OVER (PARTITION BY monthname(T_STMP)) AS <br>  entered_rows_sum_by_month<br>   FROM pyspark_poc.sales.mo_count ORDER BY monthname(T_STMP)</pre><p>This will give perfect results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_spZFcAT55wfep2s-TA5w.png" /></figure><p>Lets’ understand the query plan using snowflake feature explain using text</p><pre>explain using text <br>SELECT distinct<br>monthname(T_STMP), <br> sum(ENTERED_ROWS) OVER (PARTITION BY monthname(T_STMP)) AS entered_rows_sum_by_month<br>   FROM pyspark_poc.sales.mo_count ORDER BY monthname(T_STMP)</pre><p>This will give below result:</p><pre>GlobalStats:<br>    partitionsTotal=1<br>    partitionsAssigned=1<br>    bytesAssigned=1536<br>Operations:<br>1:0     -&gt;Result  MONTHNAME(TO_DATE(MO_COUNT.T_STMP)), SUM(MO_COUNT.ENTERED_ROWS) OVER (PARTITION BY MONTHNAME(TO_DATE(MO_COUNT.T_STMP)))  <br>1:1          -&gt;Sort  MONTHNAME(TO_DATE(MO_COUNT.T_STMP)) ASC NULLS LAST  <br>1:2               -&gt;Aggregate  groupKeys: [MONTHNAME(TO_DATE(MO_COUNT.T_STMP)), SUM(MO_COUNT.ENTERED_ROWS) OVER (PARTITION BY MONTHNAME(TO_DATE(MO_COUNT.T_STMP)))]  <br>1:3                    -&gt;WindowFunction  SUM(MO_COUNT.ENTERED_ROWS) OVER (PARTITION BY MONTHNAME(TO_DATE(MO_COUNT.T_STMP)))  <br>1:4                         -&gt;TableScan  PYSPARK_POC.SALES.MO_COUNT  ENTERED_ROWS, T_STMP  {partitionsTotal=1, partitionsAssigned=1, bytesAssigned=1536}</pre><p>Still confused : Try to draw the query plan on paper/ppt, it will be more clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67037731dcc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 2 on Cracking Data Engineering Interview at any company.]]></title>
            <link>https://medium.com/@priya.chauhangfi/day-2-on-cracking-data-engineering-interview-at-any-company-17259e364873?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/17259e364873</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 17:11:12 GMT</pubDate>
            <atom:updated>2023-03-23T17:11:12.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THPTxCvZD0Xbm_SZjDzivw.png" /></figure><p><strong>Day 2 on Cracking Data Engineering Interview at any company.</strong></p><p>Note : This series will be continued till Day 30 and it is not to target any specific company but to crack any company because at the end we should know how to get the work done once we are onboarded in the company with our technical skills.</p><p>Pre-requisite : Gear up yourself and open and online compiler or jupyter notebook</p><p>Practicing Intermediate Python questions.</p><p>Q1 : Given a text file which is comma separated having 2 columns as user_id and tip_in_inr , find out the maximum tip amount . Also print the user_id for the same</p><p>Text file looks like this :</p><pre>user_id,tip_in_inr<br>1,30.00<br>2,40.00<br>3,50.00<br>7,100.00<br>5,300.00</pre><p>Approach : convert the text file into dictionary or list and then get the maximum value out of it.</p><p>Note : Try to implement the solution without using pandas.</p><p>Here is my try :</p><pre>user = dict()<br><br>with open(r&#39;C:\Users\Priya\Downloads\user_tip.txt&#39;) as f:<br>    next(f)<br>    for line in f:<br>        data = line.split(&quot;,&quot;)<br>        filt_data=float(data[1].replace(&#39;\n&#39;, &#39;&#39;))<br>        user[data[0]] = filt_data<br>print(user)<br><br>id_with_highest_tip = max(user, key = lambda y: user[y])<br><br>print(&quot;Max tipped value is {} and tip amount is {}&quot;.format(id_with_highest_tip,user[id_with_highest_tip]))</pre><p>You can try other approaches.</p><p>Similar question was asked in Google Strategic Cloud Engineer Interview :</p><p><strong><em>Given a text file with query_id and queries, find the most_queried table</em></strong></p><p>Concepts used in this question: File Handling</p><p>To perform any operation on the file like reading or writing, first, we have to open that file. For this, we should use Python’s inbuilt function open() and at the time of opening, we have to specify the mode, which represents the purpose of the opening file.</p><pre>f = open(filename, mode)</pre><p>Where the following mode is supported:</p><ol><li><strong>r: </strong>open an existing file for a read operation.</li><li><strong>w:</strong> open an existing file for a write operation. If the file already contains some data then it will be overridden but if the file is not present then it creates the file as well.</li><li><strong>a: </strong>open an existing file for append operation. It won’t override existing data.</li><li><strong>r+:</strong> To read and write data into the file. The previous data in the file will be overridden.</li><li><strong>w+:</strong> To write and read data. It will override existing data.</li><li><strong>a+:</strong> To append and read data from the file. It won’t override existing data.</li></ol><p>Next question : Continued in Day 3</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17259e364873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 1 on Cracking Data Engineering Interview at any company.]]></title>
            <link>https://medium.com/@priya.chauhangfi/day-1-on-cracking-data-engineering-interview-at-any-company-6e3442588046?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e3442588046</guid>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 11:54:43 GMT</pubDate>
            <atom:updated>2023-03-28T18:29:13.922Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Day 1 on Cracking Data Engineering Interview at any company.</strong></p><p>Note : This series will be continued till Day 30 and it is not to target any specific company but to crack any company because at the end we should know how to get the work done once we are onboarded in the company with our technical skills</p><p>Learning Star Schema, Snowfalke Schema , fact tables and Dimension Tables, Normalization and Denormalization.</p><p>Consider below dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N825XDlCYrw3BpJjOEO_Gw.png" /></figure><p>Consider storing the above dataset into a table.</p><p>It would be called as <strong>denormalized data</strong></p><p>What the heck is denormalized data:</p><ol><li>Intentionally introduces redundancy just to have all the information in one single table.</li><li>Huge data in one single table</li><li>Less tables &gt;&gt; fewer joins</li><li>faster reads but slower writes</li><li>Used for OLAP (Online Analytical Process: performing multidimensional analysis at high speeds on large volumes of data from a data warehouse, data mart, or some other unified, centralized data store)</li></ol><p>Now you can understand what is normalization:</p><ol><li>The moment we break our tables to reduce redundancy like below, it is called as normalized, as we are decreasing the size.</li></ol><figure><img alt="Customer Table" src="https://cdn-images-1.medium.com/max/601/1*dXHnsZNXt0RGycGLZ6zZTw.png" /><figcaption>Customer_dim</figcaption></figure><figure><img alt="Sales Table" src="https://cdn-images-1.medium.com/max/489/1*G3nVgCMsBYGHSlV7c-MdxA.png" /><figcaption>Transaction_dim</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*FWcRttAiYt6MJ9QI12Vkmw.png" /><figcaption>date_dim</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Tibz-u_w4cEofzANXbBjwQ.png" /><figcaption>Item_dim</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*cpyMbuRuXOnoyZ_YIPhFXQ.png" /><figcaption>Shopping_Mode_dim</figcaption></figure><p>Similary we can have sales , items and date table separtely instead of having all of them in one single table</p><p>2. This will results in faster writes, updates, inserts</p><p>3. Joins will be required to get desired information</p><p>4. Used for OLTP</p><p>Now if someone asks you what will be the best approach for designing the database then it will be like buying a dress without considering the season, for every season, we pick the right clothes that fits our needs, similar to that, for the organizational needs we have to pick the right approach.</p><p>Suppose if you want to insert 100 records after every 1 min, then normalizing will be great option , but if someone wants to make it batch or do some analysis on history data, then denormalized will be best.</p><p><strong>Tech fact : Snowflake uses OLAP as a foundational part of its database schema and acts as a single, governed, and immediately queryable source for your data. It can write data faster and even reads it faster becasue of the way it is designed.</strong></p><p>Now the sales table that we created is nothign but acting as a Fact Tables</p><p>and all items table, customer table, Date table are acting as Dimension Tables.</p><p>Oh again new word, what is F<strong>act table : </strong>Fact tables are tables whose records are immutable “facts”, such as service logs and measurement information. Records are progressively appended into the table in a streaming fashion or in large chunks</p><p><strong>Dimension Table</strong> : Hold reference data, such as lookup tables from an entity identifier to its properties</p><ul><li>Hold snapshot-like data in tables whose entire contents change in a single transaction</li></ul><p>Dimension tables aren’t regularly ingested with new data. Instead, the entire data content is updated at once.</p><p>Placing all dimension tables at corners of stars and placing fact table in middle is called as star schema. Note that all tables are linked by a primary key such as cust_id , item_id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*E4o6dnIBnMAiNR3u3BimZg.png" /></figure><p>Now what if the dimension tables that are at the corners are further linked to other dimension tables , this will be called as Snowflake Schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3rf1ZyY7ZQYteGZHrfRxw.png" /></figure><p>Conclusion : We understood Fact Tables, Dimesnion Tables, Normalization, Denormalization, Snowflake Schema, Star Schema.</p><p>Thanks for Reading :)</p><p>Hey Data Enthusiasts, join me on upcoming webinar on Pysaprk :</p><p><a href="https://topmate.io/priya_chauhan/210580">https://topmate.io/priya_chauhan/210580</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e3442588046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect to IBM DB2 Data base with Pyspark in HDFS Shell Environment]]></title>
            <link>https://medium.com/@priya.chauhangfi/connect-to-ibm-db2-data-base-with-pyspark-in-hdfs-shell-environment-c0109926fd?source=rss-c8fbc303b39------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0109926fd</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[spar]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Priya Chauhan]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 13:13:03 GMT</pubDate>
            <atom:updated>2022-02-27T13:09:19.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extract Data From IBM DB2 Data base with Pyspark in HDFS Shell Environment</h3><figure><img alt="Priya Chauhan" src="https://cdn-images-1.medium.com/max/1024/1*p-IRJJBpLEo9D6haW7JNYg.png" /></figure><p>Hi All, In this article I have demonstrated how to extract data from IBM Db2 database and store the data in hdfs locations .</p><p>I assume that you are familiar to the pyspark . If not , you can visit <a href="https://sparkbyexamples.com/pyspark-tutorial/">https://sparkbyexamples.com/pyspark-tutorial/</a></p><p>It helped me alot.</p><p><strong>Problem Statement : Extract data from IBM DB2 and store it in the HDFS location</strong>.</p><p>Solution :</p><p>Pre-requisites :</p><p>1. IBM DB2 Driver (Download it from official Website)</p><p><strong>Role of Driver in Pyspark : </strong>Db2 Connection : Pyspark needs a jar file in order to connect to any database .In our case , it is db2 jar file which will help pyspark to build a connection to the db2 database. If you are not providing the jar file, the connection will fail even if you provide the host and port details and the code will throw an error.</p><p>2. Pyspark : If you are in hdfs environment, pyspark will be there . If not, you can visit the below website to set up the environment . In this problem statement, I am running pyspark in hdfs environment</p><p><a href="https://www.datacamp.com/community/tutorials/installation-of-pyspark">https://www.datacamp.com/community/tutorials/installation-of-pyspark</a></p><p>Solution :</p><p>Step 1 : Open your hdfs terminal with below command :</p><p>pyspark — jars /your/location//ForJar/db2jcc4.jar — num-executors 20 — executor-memory 1G — executor-cores 05</p><p>Note that I have specified the jar file , number of executors and cores.</p><p>Step 2 : Now pyspark knows where to find the jar when its asked to read data from db2 database.</p><p>Creating the SparkSession :</p><p>spark = SparkSession.builder \<br> .master(“yarn”) \<br> .appName(“ETL_Pyspark”) \<br> .getOrCreate()</p><p>I know the Spark families will think that I can provide the jar location in config option while creating the SparkSession, but trust me it didn’t work with me:(</p><p>So I have to help Pyspark to not struggle (Now I got to know, why it has a lazy Evaluation tagline:D)</p><p>Step 3 : Create the dataframe (You have to provide a structured home to load the extract data from db2)</p><p><em>test_df=spark.read.format(“jdbc”). \<br> .option(“url”,”jdbc:db2://your_db_hostname:Port/DbName:user=username;password=yourPassword;”) \<br> .option(“dbtable”,”your_table_name”) \<br> .option(“driver”,”com.ibm.db2.jcc.DB2Driver”) \<br> .load()</em></p><p>Step 3 : Yes! you can read the data now(Make sure you have permission to see the data from its original owner (DB2 Admin))</p><p>— test_df.show()</p><p>— test_df.count()</p><p>Step 4 : Store your dataframe in csv format(your choice, it can be parquet or any allowed format in pyspark)</p><p>test_df.write.csv(“/your/hdfs/location”)</p><p>Now, you have extracted and loaded the data in hdfs shell using pyspark.</p><p>Now you can do your transformations and load the data in your target db table, in my case it is postgres.</p><p>Thank You! Hope it helped you.</p><p>Please click on the clap icon and follow for more such content!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0109926fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>