<?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 Saurabh Soni on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Soni on Medium]]></description>
        <link>https://medium.com/@srbsoni?source=rss-7f00fba8b20d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RLfvO8ClkORUNlvy.jpg</url>
            <title>Stories by Saurabh Soni on Medium</title>
            <link>https://medium.com/@srbsoni?source=rss-7f00fba8b20d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:05:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srbsoni/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[Spark Transformation (Dataframe creation)]]></title>
            <link>https://medium.com/@srbsoni/spark-transformation-dataframe-creation-52899a089919?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/52899a089919</guid>
            <category><![CDATA[spark-transformations]]></category>
            <category><![CDATA[spark-dataframe]]></category>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 07:03:01 GMT</pubDate>
            <atom:updated>2026-09-19T07:03:01.192Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing from <a href="https://medium.com/@srbsoni/apache-spark-higher-level-apis-29d3cd779a1a">Apache Spark — Higher Level APIs</a></p><h3><strong>Ways to Enforce Schema</strong></h3><p><strong>1. Schema option- Schema DDL</strong></p><pre>### Defining data type<br>orders_schema = &#39;order_id long, order_date date, cust_id long, order_status string&#39;<br><br>### Importing the data from declared data types<br>df = spark.read \<br>.format(&quot;csv&quot;) \<br>.schema(orders_schema) \<br>.load(&quot;/public/trendytech/datasets/orders_sample1.csv&quot;)</pre><p>If there is a data type issue, say integer data type is assigned to a string field, then null values will be assigned</p><p><strong>2. StructType</strong></p><pre>from pyspark.sql.types import *<br><br>orders_schema_struct = StructType([<br>StructField(&quot;orderid&quot;,LongType()),<br>StructField(&quot;orderdate&quot;,DateType()),<br>StructField(&quot;customerid&quot;,IntegerType()),<br>StructField(&quot;orderstatus&quot;,StringType()),<br>])<br><br>df = spark.read \<br>.format(&quot;csv&quot;) \<br>.schema(orders_schema_struct) \<br>.load(&quot;/public/trendytech/datasets/orders_sample1.csv&quot;)</pre><h4>How to handle Date Type</h4><p>Default format of date type in Spark is <strong>yyyy-mm-dd<br></strong> If the date format is different from the one mentioned above, then it will lead to Parse Error</p><p><strong>a. While loading the data in dataframe</strong></p><pre>### While loading the dataframe<br>### If the data is in format mm-dd-yyyy (01-27-1989)<br><br>df = spark.read \<br>.format(&quot;csv&quot;) \<br>.schema(orders_schema) \<br>.option(&quot;dateFormat&quot;, &quot;mm-dd-yyyy&quot;) \<br>.load(&quot;/public/trendytech/datasets/orders_sample2.csv&quot;)</pre><p>b. Load it as string and then transform (withColumn → for column transformation)</p><pre>### Import order_date as string <br>orders_schema = &#39;order_id long, order_date string, cust_id long, order_status string&#39;<br><br>### Load the data<br>df = spark.read \<br>.format(&quot;csv&quot;) \<br>.schema(orders_schema) \<br>.load(&quot;/public/trendytech/datasets/orders_sample2.csv&quot;)<br><br>### Apply transformation<br>from pyspark.sql.functions import to_date<br><br>new_df = df.withColumn(&quot;order_date_new&quot;, to_date(&quot;order_date&quot;, &quot;mm-dd-yyyy&quot;))</pre><h3>Types of read modes</h3><ol><li><strong>Permissive</strong>: This is the <strong>default read mode in spark</strong>. If Spark is unable to parse any data due to dataype mismatch then it makes it null without impacting other results<br>For Example — if order_date is in “mm-dd-yyyy” format and correct date type is not defined in schema then order_date column will be null</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*lSTJsgp1hTmDUqSBKTdKjg.png" /><figcaption>Permissive Mode</figcaption></figure><p><strong>2. FailFast: </strong>Throws an error as soon as any malformed record is seen</p><p><strong>3. dropmailformed: </strong>Drops any malformed records and rest of the records will be processed. <br>Example — Consider there 10 records in orders table but cust_id for 2 records (rows) are null then only 8 records will be present in this mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*pS9QONTrDV9iqBmIVtVCdA.png" /></figure><h3>Different ways of creating a Dataframe</h3><ol><li><strong>spark.read</strong></li></ol><pre>df = spark.read \<br>.format(&quot;csv&quot;) \<br>.option(&quot;header&quot;,&quot;true&quot;) \<br>.option(&quot;inferschema&quot;,&quot;true&quot;) \<br>.load(&quot;&lt;file-path&gt;&quot;)</pre><p><strong>2. spark.sql (Results of a Spark SQL query is a Dataframe)</strong></p><pre>df = spark.sql(“select * from &lt;table-name&gt;”)</pre><p><strong>3. spark.table</strong></p><pre>df = spark.table(“&lt;table-name&gt;”)</pre><p><strong>4. spark.range → Range gives a one column dataframe</strong></p><pre>### if range size is 5, then dataframe will have 1 column 0,1,2,3,4 (5 not included)<br>df = spark.range(&lt;range-size&gt;) <br><br>### if start-range is 0 &amp; end-range is 5, <br>### then dataframe will have 1 column 0,1,2,3,4<br>df = spark.range(&lt;start-range&gt;, &lt;end-range&gt;)<br><br>### if start-range is 0 &amp; end-range is 5 &amp; increment is 2, <br>### then dataframe will have 1 column 0,2,4<br>df = spark.range(&lt;start-range&gt;, &lt;end-range&gt;, &lt;increment&gt;</pre><p><strong>5. Create dataframe from a local list</strong></p><pre>### This step will create a DF with default column names &#39;_1&#39;,&#39;_2&#39; <br>### and default data types such as long or string<br>df = spark.createDataFrame(list)</pre><p>To explicitly define column names and schema</p><pre>### &quot;toDF&quot; transformation can help in explicitly define column names<br>df = spark.createDataFrame( list ).toDF(&lt;column-name&gt;)</pre><p>Creating DF using define schema and column name</p><pre>### Define column name and schema<br>schema = ‘ &lt;column-name-1&gt; &lt;datatype-1&gt;,&lt;column-name-2&gt;&lt;datatype-2&gt;,... ’<br><br>### Creating dataframe<br>df = spark.createDataFrame( list, schema )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-SDrU5SC5WyAcz0d8Y68w.png" /><figcaption>create a dataframe using list and defined schema</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52899a089919" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark — Higher Level APIs]]></title>
            <link>https://medium.com/@srbsoni/apache-spark-higher-level-apis-29d3cd779a1a?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d3cd779a1a</guid>
            <category><![CDATA[spark-higher-level-apis]]></category>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 06:27:47 GMT</pubDate>
            <atom:updated>2026-09-15T06:30:50.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing from <a href="https://medium.com/@srbsoni/apache-spark-core-apis-part-2-5fac6ec42a8d">Apache Spark Core APIs</a></p><p>In Higher Level APIs spark engine is provided with <strong>more context to handle the data effectively</strong> with the help of metadata information.</p><ol><li><strong>Spark SQL/ Spark Table</strong>- <strong>Is Persistent over different sessions</strong> as data files are <strong>stored on the disk</strong> (any storage like Datalake / HDFS / S3) and the <strong>schema / metadata is in a Metastore </strong>(Database)</li><li><strong>Dataframes</strong>- are in the form of <strong>RDDs with some structure / schema</strong> that is <strong>not persistent</strong> as it is available only in that particular session. <strong>Data is stored in memory and Metadata is saved in a temporary metadata catalog</strong>.</li></ol><h3>Working with Dataframes</h3><ol><li>Load the data file and create a Spark Dataframe</li><li>Apply Transformations</li><li>Write the results back to Storage.</li></ol><p>Note: <strong>Spark Session is an entry point</strong> to the Spark Cluster in case of <strong>Higher Level APIs</strong>. Spark Context is for lower level RDDs</p><p>Standard way to create a Dataframe:</p><pre>df = spark.read \<br>.format(&quot;csv&quot;) \<br>.option(&quot;header&quot;,&quot;true&quot;) \<br>.option(&quot;inferschema&quot;,&quot;true&quot;) \<br>.load(&quot;&lt;file-path&gt;&quot;)<br><br>####### OR #######<br>####### CSV #######<br>df = spark.read \<br>.csv(“&lt;file-path&gt;”, header = “true”, inferSchema = “true”)<br><br>####### JSON #######<br>df = spark.read \<br>.json(“&lt;file-path&gt;”)<br><br>####### parquet #######<br>df = spark.read \<br>.parquet(“&lt;file-path&gt;”)</pre><h4>Dataframes and Spark SQL table</h4><ol><li>SparkSQL table from dataframe</li></ol><pre>orders_df.createOrReplaceTempView(&quot;orders&quot;)</pre><p>orders_df → <strong>Dataframe</strong><br><strong>createOrReplaceTempView </strong>→ function to convert dataframe to sparkSQL table view<br><strong>“orders”</strong> → SparkSQL table/view distributed across the cluster<br><em>Now, we can execute normal SQL queries on the SparkSQL table view created from a Dataframe</em></p><pre>filtered_df = spark.sql(&quot;select * from orders where order_status = &#39;CLOSED&#39; &quot;)</pre><p>2. Dataframe from SparkSQL table<br>df = spark.read.table(“orders”)</p><p>Other alternative to create a SparkSQL table from Dataframe:</p><ul><li><strong>createOrReplaceTempView</strong>- creates a table. If the table exists, then it replaces the existing table without throwing any error (will create table/view only for the active notebooks and will not be visible in other applications)</li><li><strong>createTempView</strong>- creates a table. If the table already exists, then it errors out, stating the table already exists (will create table/view only for the active notebooks and will not be visible in other applications)</li><li><strong>createGlobalTempView</strong>- The table view will be visible across other applications as well. If the table already exists, then it errors out, stating the table already exists (can be used in other notebooks/sessions)</li><li><strong>createOrReplaceGlobalTempView</strong>- replaces any existing table view with the newly created table. Creating a Spark Table If a table is created without selecting the Database in which it has to be created, it will be created under the Default Database (can be used in other notebooks/sessions)</li></ul><h3>Working with Spark Table/Spark SQL</h3><pre>##### To create Database <br>spark.sql(&quot;create database if not exists &lt;database name&gt; &quot;) <br><br>##### To view the database <br>spark.sql(&quot;show databases&quot;) <br><br>##### To view the databases with a certain pattern in their name <br>spark.sql(&quot;show databases&quot;).filter(&quot;namespace like &#39;%&#39;&quot;).show() <br><br>##### To view the tables <br>spark.sql(&quot;show tables&quot;).show()<br><br>##### Create a table inside a database<br>spark.sql(&quot;create table &lt;dbname&gt;.&lt;tablename&gt; <br>(order_id integer, order_date datetime, customer_name string)&quot;)<br><br>#### Insert in created table from default temp view table<br>spark.sql(&quot;insert into &lt;dbname&gt;.&lt;tablename&gt; select * from orders&quot;)<br><br>#### description of the table (for schema only)<br>spark.sql(&quot;describe table &lt;dbname&gt;.&lt;tablename&gt;&quot;).show()<br><br>#### extended description of the table (inclused schema, owner, created_time, location etc.) <br>spark.sql(&quot; describe extended &lt;dbname&gt;.&lt;tablename&gt;)</pre><p>If a table is created without selecting the Database in which it has to be created, it will be created under the Default Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*gMn8gAXNSHHCLlApeenTGw.png" /><figcaption><strong>Extended description of the table</strong></figcaption></figure><p>In HDFS or data lake, DB and tables are stored as <br><strong>&lt;hdfs location of DB&gt;/warehouse/&lt;databasename.db&gt;/&lt;tablename&gt;/files</strong></p><p><strong>Tables Types:</strong></p><ol><li>Managed Table</li><li>External Table</li></ol><p><strong>Managed Table — <br>- </strong>Create an empty table → Load the data from a temporary view / table<br>- <strong>When this table is dropped, both the data and metadata is lost</strong></p><pre>spark.sql(“create table itv005857_retail.orders(order_id integer, order_date<br>string, customer_id integer, order_status string) using csv”)</pre><p><strong>External Table — <br>- </strong>The data is already present in a specific location and <strong>a structure has to be created</strong> to get a tabular view <br>- When this <strong>table is dropped, only the metadata is lost </strong>as you are not the owner of the data</p><pre>spark.sql(“create table itv005857_retail.orders(order_id integer, order_date<br>string, customer_id integer, order_status string) <br>using csv location<br>‘/public/trendytech/retail_db/orders’ ”)</pre><p>On an external table, <strong>delete and update</strong> will not work as it would require to change the file. But <strong>insert operation</strong> will work and a new records will come in the new file</p><p>Functions that change the original dataframe are either action and transformation, and functions which change the data are transformations and the ones which gives/show output are action.<br>- Count() can as action if used just to count rows but if it is used with GroupBy then count will come as group by with the columns so now it acts as transformation<br>- Functions such as printSchema or createtempview are just utility functions as it doesn’t change the raw dataframe in anyway</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d3cd779a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark Core APIs — Part 2]]></title>
            <link>https://medium.com/@srbsoni/apache-spark-core-apis-part-2-5fac6ec42a8d?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fac6ec42a8d</guid>
            <category><![CDATA[apache-spark-core-apis-2]]></category>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 18:23:33 GMT</pubDate>
            <atom:updated>2026-09-10T05:44:18.586Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing from <a href="https://medium.com/@srbsoni/apache-spark-basics-part-1-0c003d321fbf?postPublishedType=repub">Apache Spark Core APIs Part 1</a></p><p><strong>Types of transformation<br>Narrow — </strong>No shuffling involved <br>(the transformed data will not be transferred to a different machine but resides on the same machine)<br><strong>Wide </strong>— Shuffling involved <br>(the transformed data is transferred to a different machine for final global aggregation)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*242nElP09SgkTk6lLXK6eA.png" /></figure><p><strong>Wide Transformations</strong>: <br>- Involve shuffle which is a <strong>costly transformation</strong>. <br>- Should be <strong>minimized</strong> and performed towards the end after the data is narrowed down to almost the desired state and thereby requires only minimal data to be transferred</p><h3>Visualizing Spark Jobs on History Server</h3><ul><li>Jobs will be visible on the history server only after they are terminated</li><li>History Server URL- <a href="http://m02.itversity.com:18080/">http://m02.itversity.com:18080/</a> (for the current course)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*HXtOljlju3kg9asp-VDbxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*KgyNs-cLSM-Bj3zCMCysIQ.png" /><figcaption>Terms on Spark History Server</figcaption></figure><p><strong>reduce vs reduceByKey<br>- reduce is an action</strong> while <strong>reduceByKey is a transformation</strong><br>- <strong>reduce give the single value </strong>as a result while <strong>reduceByKey’s result depends on # keys</strong><br>- Output of reduce doesn’t need any parallelism as it’s single value while <strong>reduceByKey might still need parallelism hence it’s results are stored in cluster</strong></p><h4><strong>reduceByKey vs groupByKey</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*OzVJ5b4f-8HJ4f_gOV7wig.png" /></figure><p>Let’s understand with an example : <br>- consider a 1000 node cluster and we need to process 1TB (8000 blocks) orders data <br>- each worker node will have 8 blocks and RDD will have 8000 partitions<br>Since <strong>groupByKey doesn’t do local aggregation, a lot of data will be shuffled</strong> and can cause runtime error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*KdgCC7Q01mGzXKPpgL7fIg.png" /></figure><p><strong>groupByKey is useful when we need the complete collection of values for each key</strong></p><p><strong>Spark Join<br>- S</strong>park RDD Joins are wide transformations that involves data shuffling over the network <br>- They could lead to performance issues if not designed carefully as it involves a lot of data transfer <br>- Data has to be present on the same partition in order to perform Join.</p><p><strong>Broadcast Join<br>- </strong>Normal Join is a costly operation as it is a wide transformation and involves a lot of data shuffle. To overcome this issue, Broadcast join provides a more optimized solution.<br>- <strong>The complete smaller dataset is broadcasted across all the nodes, every individual node is capable of performing join locally</strong>.<br>-No Shuffling happens over the network for broadcast join<br>-No additional stage is created in the DAG as there is no shuffling involved in a broadcast join.<br>Example — The larger dataset ( orders of ~ 1GB ) is distributed across the cluster. Whereas, the smaller dataset ( customers of 1MB ), the complete copy of the dataset, is made available on every machine on the cluster. This hugely reduces the shuffling of Data and thereby optimizing the performance.</p><h4>Repartition vs Coalesce</h4><p>Suppose there is a <strong>need to increase or decrease the number of partitions</strong>, then repartition can be used as it can do both, i.e., increase / decrease the no.of partitions in a RDD</p><pre>repartitioned_rdd = base_rdd.repartition(&lt;increased partitions number&gt;<br>repartitioned_rdd = base_rdd.repartition(&lt;decreased partitions number&gt;</pre><p><strong>Scenario 1 : When to increase the number of partitions?</strong><br>- Say you have a 5GB file =&gt; 40 blocks ( = 40 partitions) running on a 100 node cluster.<br>- Since there are only 40 partitions, they will run on 40 nodes and the remaining 60 nodes are idle. <br>- This leads to underutilization of resources. In such cases, <strong>the partitions can be increased to achieve more parallelism.</strong></p><p>Scenario 2 : When to decrease the number of partitions ?<br>- Say you have 1 TB file → 8000 blocks ( = 8000 partitions) running on a 100 node cluster. Each node will handle around 80 partitions. <br>- After applying transformations like- filter, the data would reduce significantly ( say from 128MB[default] to 1MB ) <br>- This will lead to a lot of sparse data and also would be tedious to maintain large no.of partitions. <br>- It would be <strong>more efficient to have few number of completely filled partitions than having large no.of sparsely filled partitions</strong></p><h4>Repartition does a complete reshuffle of data while changing the no.of partitions with the intent to have equal sized partitions</h4><p><strong>Coalesce</strong> on the other hand tries to <strong>merge the partitions on the same node to form a new partition that could be of unequal sizes but the shuffling is avoided</strong>. Therefore, <strong>coalesce is preferred when decreasing the number of partitions</strong> as it avoids shuffling of data</p><h4>Cache</h4><ul><li>Suppose there are multiple costly transformations that need to be executed</li><li>When an action is called for the first time, all the transformations are executed. If the results of these transformations are cached, then when an action is called again, the cached results of transformations are used without having to re-execute all the transformations again.</li></ul><pre>rdd_from_where_alot_transformation.cache()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fac6ec42a8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark Core APIs— Part 1]]></title>
            <link>https://medium.com/@srbsoni/apache-spark-basics-part-1-0c003d321fbf?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c003d321fbf</guid>
            <category><![CDATA[basics-of-apache-spark]]></category>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 06:05:34 GMT</pubDate>
            <atom:updated>2026-09-09T18:24:03.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basics</h3><blockquote>RDD — Resilient distributed dataset, it is the basic unit that holds the data in spark.<br>Assume you have a 4 node cluster and a file which is divided into 4 blocks, so each node holdes 1 cluster, now when each of these blocks are loaded to memory (RAM) of the worker node it is called <strong>partition</strong>, so for our use case we have 4 partitions and <strong>all these partitions together is called RDD.<br>So RDD is a distributed collection in memory.</strong></blockquote><blockquote>There are <strong>two kinds of operations in Apache Spark</strong>:<br>1. Transformation<br>2. Action</blockquote><blockquote>Let’s understand with an example:<br>Step 1 →Assume the above case a file with 4 data blocks when loaded to memory becomes RDD, say RDD1 <br>Step 2 → now say there are bunch of transformations are happening on this RDD1 (map, filter etc.) and it becomes RDD2<br>Step 3 → Finally we need to get the results so we run RDD2.collect()<br><strong>Step 1 &amp; 2 are Transformations<br>Step 3 is an action<br>- </strong>All <strong>transformations are lazy</strong> while actions are now, so <strong>transformations become action plan </strong>and get executed when actions are called<br>- For <strong>every transformation a new RDD is created</strong>, and one can’t make change to an existing RDD <strong>as RDDs are immutable <br>- </strong>If an RDD (say RDD2) gets failed, system applies the same transformation on the previous RDD (RDD1) and gets the RDD2 back, hence the “R” in RDD means <strong>Resilient </strong>as it is reslient to failures</blockquote><blockquote>Q. What happens if the initial RDD (like RDD1) fails? How does Spark recover it?<br>If rdd1 is from a file → Spark reads the file again. <br><strong>If rdd1 is only from memory → Spark cannot recover it if lost</strong>.</blockquote><h4><strong>Now above mentioned steps are called a DAG (directed cyclic graph)</strong></h4><blockquote>Why are transformations lazy? — Lazy helps to optmise the execution of the DAG, let’s understand the pseudo code <br>step1 → Load the files (of 1 billion records) <br>step2 → Perform a map operation<br>step 3 → Perform a filter operation<br>step 4 → collect the data or print the data</blockquote><blockquote>Now if transformations were not lazy, it would have loaded a file of 1 billion records in the memory, performed map operation on 1 billion rows and then filtered, which would have given say 10 records<br>But internally what spark does it is filters the records and then perform map operations, so 1 billion records are only processed once and then only filtered records are mapped</blockquote><p><em>Mental note →Write another blog on lazy operations!!</em></p><p>Spark has two level of APIs:<br>1. Layer 1 of Spark : Spark’s core APIs<br>- Works on RDD level<br>- Works with python, R, Scala, Java</p><p>2. Layer 2 of Spark: Higher level APIs<br>- Works on dataframes, SQL, structed streaming, MLlib, GraphX</p><h4><strong>Sparkcontext vs Sparksession</strong></h4><p>Front door to Spark</p><ul><li><strong>SparkContext</strong> is the entry point to Spark Core. It establishes the <strong>connection between a Spark application and the cluster</strong>, coordinates execution, and provides APIs for creating and manipulating RDDs</li><li><strong>SparkSession</strong> is main <strong>entry point to modern PySpark applications. </strong>It provides APIs to work with <strong>DataFrames, Spark SQL, and other Spark functionality</strong>, while also giving access to the <strong>underlying SparkContext for RDD-based operations</strong></li></ul><h3>Basic PySpark</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*Tzcd6AOTSJXLIQcagwzPrQ.png" /></figure><ol><li>parallelize() is a method of SparkContext used to convert a local Python collection (like a list) into a distributed RDD.</li></ol><pre><br>data = [1, 2, 3, 4, 5, 6, 7, 8]<br><br>You can create an RDD with multiple partitions:<br>rdd = sc.parallelize(data, 4)<br><br>Conceptually:<br>RDD<br>│<br>├── Partition 1 → [1, 2]<br>├── Partition 2 → [3, 4]<br>├── Partition 3 → [5, 6]<br>└── Partition 4 → [7, 8]</pre><p>2. Map: <strong>map()</strong> is a transformation used to apply a function to <strong>every element of an RDD</strong> and return a new RDD.</p><p>Basic syntax: rdd.map(lambda x: …)</p><pre>result = rdd.map(lambda x: x * 2)<br>result = rdd.map(square)<br>result = rdd.map(lambda x: x.upper())</pre><p>map() can change the structure</p><pre>rdd = sc.parallelize([&quot;John,25&quot;, &quot;Mike,30&quot;, &quot;Sarah,28&quot;])<br>result = rdd.map(lambda x: x.split(&quot;,&quot;))<br>print(result.collect())<br>[[&#39;John&#39;, &#39;25&#39;], [&#39;Mike&#39;, &#39;30&#39;], [&#39;Sarah&#39;, &#39;28&#39;]]</pre><p>3. Reduce: <strong>reduce() combines/aggregates all elements of an RDD into a single value</strong> by repeatedly applying a function. <strong>reduce() is an Action</strong></p><pre>rdd.reduce(function)<br><br>from pyspark import SparkContext<br>from functools import reduce<br><br>sc = SparkContext.getOrCreate()<br><br>rdd = sc.parallelize([1, 2, 3, 4, 5])<br><br>result = rdd.reduce(lambda x, y: x + y)<br><br>print(result)</pre><p>Suppose the RDD has two partitions:</p><pre>Partition 1: [1, 2, 3]<br>Partition 2: [4, 5]<br><br>Spark can first reduce within each partition<br><br>Partition 1 → 1 + 2 + 3 = 6<br>Partition 2 → 4 + 5     = 9<br><br>then combine<br>6 + 9 = 15</pre><p>4. reduceByKey: reduceByKey() is an <strong>RDD transformation</strong> used to aggregate values that have the <strong>same key (</strong>groups values based on their keys<strong>). </strong>This <strong>map-side combining</strong> reduces the amount of data transferred during the shuffle.</p><pre>rdd = sc.parallelize([<br>    (&quot;apple&quot;, 10),<br>    (&quot;banana&quot;, 20),<br>    (&quot;apple&quot;, 15),<br>    (&quot;banana&quot;, 5),<br>    (&quot;orange&quot;, 30)<br>])<br><br>result = rdd.reduceByKey(lambda x, y: x + y)<br><br>print(result.collect())<br><br>[(&#39;apple&#39;, 25), (&#39;banana&#39;, 25), (&#39;orange&#39;, 30)]<br><br>Spark effectively does:<br><br>apple  → 10 + 15 = 25<br>banana → 20 + 5  = 25<br>orange → 30       = 30</pre><p>5. filter: filter() is an <strong>RDD transformation</strong> used to keep only the elements that satisfy a given condition.</p><pre>EXAMPLE 1:<br>rdd = sc.parallelize([1, 2, 3, 4, 5, 6])<br><br>result = rdd.filter(lambda x: x &gt; 3)<br><br>print(result.collect())<br><br>[4, 5, 6]<br><br>EXAMPLE 2: Filtering key value RDDs<br>rdd = sc.parallelize([<br>    (&quot;John&quot;, 5000),<br>    (&quot;Mike&quot;, 3000),<br>    (&quot;Sarah&quot;, 7000)<br>])<br><br>To keep employees earning more than 4,000:<br><br>result = rdd.filter(lambda x: x[1] &gt; 4000)<br><br>print(result.collect())<br><br>[(&#39;John&#39;, 5000), (&#39;Sarah&#39;, 7000)]</pre><p>6. sortBy() allows you to specify <strong>any function/expression to determine the sorting key</strong>. It is a transformation</p><pre>rdd = sc.parallelize([5, 2, 8, 1, 3])<br><br>result = rdd.sortBy(lambda x: x, ascending=False)<br><br>print(result.collect())<br><br>[8, 5, 3, 2, 1]<br><br>Sort by a particular attribute:<br><br>rdd = sc.parallelize([<br>    (&quot;John&quot;, 5000),<br>    (&quot;Mike&quot;, 3000),<br>    (&quot;Sarah&quot;, 7000)<br>])<br><br>result = rdd.sortBy(lambda x: x[1])<br><br>print(result.collect())<br><br>[<br>    (&quot;Mike&quot;, 3000),<br>    (&quot;John&quot;, 5000),<br>    (&quot;Sarah&quot;, 7000)<br>]</pre><p>7. sortByKey() is specifically for <strong>key-value RDDs</strong>. It is a transformation</p><pre>rdd = sc.parallelize([<br>    (3, &quot;C&quot;),<br>    (1, &quot;A&quot;),<br>    (2, &quot;B&quot;)<br>])<br><br>rdd.sortByKey().collect()<br><br>[(1, &quot;A&quot;), (2, &quot;B&quot;), (3, &quot;C&quot;)]</pre><p>8. distinct() is an <strong>RDD transformation</strong> used to remove duplicate elements from an RDD and return only <strong>unique values</strong>. Spark has to compare records across partitions, so <strong>distinct() generally involves a shuffle</strong>.</p><pre>rdd = sc.parallelize([<br>    (&quot;A&quot;, 10),<br>    (&quot;B&quot;, 20),<br>    (&quot;A&quot;, 10),<br>    (&quot;C&quot;, 30)<br>])<br><br>rdd.distinct().collect()<br><br>[(&quot;A&quot;, 10), (&quot;B&quot;, 20), (&quot;C&quot;, 30)]</pre><p>9. countByValue() is an <strong>RDD action</strong> that counts how many times <strong>each unique value</strong> occurs in an RDD. It works directly on <strong>individual values </strong>and don’t require creation of key value pairs<br>- countByValue() <strong>returns the result to the driver</strong>, whereas <br>- reduceByKey() <strong>returns another RDD that remains distributed</strong>. <br>That’s one reason <strong>reduceByKey() is more appropriate for large-scale/custom aggregations</strong>, while countByValue() is convenient for simple frequency counts when the <strong>number of distinct values is manageable</strong>.</p><pre>countByValue() --&gt; &quot;Just count occurrences&quot;<br>reduceByKey() --&gt; &quot;Aggregate values associated with each key&quot;</pre><pre>rdd = sc.parallelize([&quot;A&quot;, &quot;B&quot;, &quot;A&quot;, &quot;C&quot;, &quot;A&quot;])<br><br>rdd.countByValue()<br><br>{<br>    &#39;A&#39;: 3,<br>    &#39;B&#39;: 1,<br>    &#39;C&#39;: 1<br>}</pre><p>while in reduceByKey:</p><pre>rdd = sc.parallelize([<br>    (&quot;A&quot;, 10),<br>    (&quot;B&quot;, 20),<br>    (&quot;A&quot;, 10),<br>    (&quot;C&quot;, 30)<br>])<br><br>mapped_rdd = rdd.map(lambda x:(x,1))<br>results = mapped_rdd.reduceByKey(lambda x,y: x+y)<br>results.collect()</pre><p>Let’s understand with an example:</p><pre>words =<br>(&quot;big&quot;,&quot;Data&quot;,&quot;Is&quot;,&quot;SUPER&quot;,&quot;Interesting&quot;,&quot;BIG&quot;,&quot;data&quot;,&quot;IS&quot;,&quot;A&quot;,&quot;Trending&quot;,&quot;techn<br>ology&quot;)<br>## Converting to a distributed RDD<br>words_rdd = spark.sparkContext.parallelize(words)<br><br>## Using map function to normalising different cases of words to lower<br>words_normalized = words_rdd.map(lambda x:x.lower())<br><br>## Using map function to get key value pair with value 1 for each word as a key<br>mapped_words = words_normalized.map(lambda x:(x,1))<br><br>## get the count for each key (words in this case) <br>aggregated_result = mapped_words.reduceByKey(lambda x,y:x+y)<br><br>## see the final results<br>aggregated_result.collect()</pre><p>We can also chain all the commands and execute in one go</p><pre>spark.sparkContext.parallelize(words).map(lambda x:x.lower()).map(lambda<br>x:(x,1)).reduceByKey(lambda x,y:x+y).collect()<br><br>## Cleaner way of writing the same - &quot;\&quot; means new line<br>result = spark. \<br>sparkContext. \<br>parallelize(words). \<br>map(lambda x:x.lower()). \<br>map(lambda x:(x,1)). \<br>reduceByKey(lambda x,y:x+y)<br><br>## Then<br>results.collect()</pre><blockquote><strong>Check number of RDD Partitions:</strong></blockquote><blockquote><strong>&lt;rdd&gt;.getNumPartitions() </strong>is used to see number of partitions</blockquote><blockquote>- Consider there is file of 1 GB in HDFS, so # blocks would be 1 GB/128MB (default block size of 128MB) → 8 Blocks, so # of partitions will also be 8<br><strong># RDDpartitions = # Blocks in HDFS<br></strong><br><strong>- </strong>If the file size is less than 128 MB, then # blocks can be checked “spark.SparkContext.<strong>defaultMinPartitions</strong>” <strong>which is set as 2 by default<br>- “</strong>spark.SparkContext.<strong>defaultParallelism</strong>” is a property that indicates the # default tasks that can run in parallel</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c003d321fbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Map Reduce Understanding]]></title>
            <link>https://medium.com/@srbsoni/map-reduce-understanding-d3081c068244?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3081c068244</guid>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 19:57:15 GMT</pubDate>
            <atom:updated>2026-09-07T19:57:46.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>MapReduce execution process</h3><p>Overall flow:</p><h4>INPUT DATA<br> ↓<br> MAP<br> ↓<br> COMBINER<br> ↓<br> SHUFFLE<br> ↓<br> SORT<br> ↓<br> REDUCER<br> ↓<br>FINAL OUTPUT</h4><h4>1. MAP — Gives Parallelism</h4><p>The <strong>Map phase</strong> processes different pieces/partitions of data in parallel.</p><pre>INPUT: <br>Partition 1 → &quot;apple apple banana&quot;<br>Partition 2 → &quot;banana apple&quot;<br><br>Mapper produces key-value pairs:<br><br>Partition 1:<br>(apple, 1)<br>(apple, 1)<br>(banana, 1)<br><br>Partition 2:<br>(banana, 1)<br>(apple, 1)<br><br>Note: The key is the word and the value is 1</pre><p>Gives parallelism means different partitions can be processed simultaneously:</p><pre>              INPUT<br>          /            \<br>         ↓              ↓<br>     Mapper 1        Mapper 2<br>         ↓              ↓<br>      (apple,1)      (banana,1)<br>      (apple,1)      (apple,1)<br>      (banana,1)</pre><h4>2. COMBINER — Local Aggregation</h4><p>The <strong>Combiner</strong> performs a <strong>local aggregation at the mapper end</strong> before data is sent across the network.</p><pre>For Partition 1:<br>(apple,1)<br>(apple,1)<br>(banana,1)<br><br>becomes:<br>(apple,2)<br>(banana,1)<br><br>Partition 2:<br>(banana,1)<br>(apple,1)<br><br>becomes:<br>(banana,1)<br>(apple,1)<br><br>so instead of sending:<br>apple,1<br>apple,1<br>banana,1<br>banana,1<br>apple,1</pre><h4>3. SHUFFLE — Sending Mapper Output to Reducers</h4><p>Now Spark needs to bring all values belonging to the same key together.</p><pre>We have:<br>Mapper 1 → (apple,2), (banana,1)<br>Mapper 2 → (banana,1), (apple,1)<br><br>The shuffle redistributes the data:<br><br>Apple → (2,1) → Reducer<br>Banana → (1,1) → Reducer</pre><p>In case of multiple reducers: Same keys must go to the same reducer.</p><pre>apple → Reducer 1<br>apple → Reducer 1<br><br>banana → Reducer 2<br>banana → Reducer 2</pre><h4>4. SORT — Organizing Data on the Reducer Side</h4><p>After shuffle, the reducer receives data organized by key.</p><pre>Reducer:<br><br>apple  → [2, 1]<br>banana → [1, 1]</pre><p>The sorting/grouping ensures that values belonging to the same key are together so that the reducer can process them.</p><p>Shuffle → Bring same keys together<br>Sort → Organize/group them by key</p><h4>5. REDUCER — Final Aggregation</h4><p>Now the reducer applies the aggregation function.</p><pre>apple  → 2 + 1 = 3<br>banana → 1 + 1 = 2<br><br>FINAL OUTPUT:<br>(apple, 3)<br>(banana, 2)<br><br>With multiple reducers:<br><br>             SHUFFLE<br>                ↓<br>       ┌────────┴────────┐<br>       ↓                 ↓<br>  Reducer 1          Reducer 2<br>   apple              banana<br>     ↓                   ↓<br>  (apple,3)          (banana,2)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3081c068244" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stuff I am learning]]></title>
            <link>https://medium.com/@srbsoni/stuff-i-am-learning-aff095acff6f?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff095acff6f</guid>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 15:31:47 GMT</pubDate>
            <atom:updated>2026-09-06T18:26:39.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing from basics of <a href="https://medium.com/@srbsoni/stuff-i-am-learning-f0c26ef5c317">big data</a> and <a href="https://medium.com/@srbsoni/stuff-i-am-learning-c050d38ac466">linux commands</a></p><p><strong>HDFS commands</strong></p><blockquote><strong>HDFS commands are linux based commands</strong><br>If you want to execute a Linux command on a distributed environment, all you have to do is prefix it with : “<strong>hadoop fs” Or “hdfs dfs” </strong>(will also give the list of all commands)</blockquote><blockquote><strong>- </strong>Currently we are in the <strong>gateway node</strong> (can also be said as <strong>local not HDFS) </strong>and home directory is “/home/itv028003” while in HDFS it is “/user/itv028003”</blockquote><blockquote>- A gateway node (or edge node) and a local machine are completely separate components. <br>● Local Machine: The personal computer or laptop used to connect to the cluster. It sits entirely outside the cluster network. <br>● Gateway Node: <strong>A dedicated server that acts as the entry point into the cluster. </strong>It is part of the cluster network but <strong>does not store data blocks</strong> (unlike HDFS DataNodes) or <strong>manage cluster resources</strong> (unlike Master Nodes).<strong> </strong><br>The gateway node has Hadoop and Spark client binaries installed,<strong> allowing users to run commands, submit jobs, and interact with HDFS safely without logging directly into the master or data nodes.</strong></blockquote><blockquote>- When we command with hadoop fs or hdfs dfs it interacts with <strong>name node<br>- </strong>hadoop fs -ls / (root directory of hdfs) <br>- hadoop fs -ls -t -r / (reverse time) <br>- hadoop fs -ls -S -h /order_results (based on size)<br>- hadoop fs -ls /user | grep itv872598<br>- hadoop fs -mkdir /user/itv005857/dir1/dir2 (will not work) <br>- hadoop fs -mkdir -p /user/itv005857/dir1/dir2 (p: pattern) and this will work<br>- bring file from my local to hdfs /data/trendytech bigLog.txt from local to hdfs (data folder) <br>“put” or “copyFromLocal” <br>- hadoop fs -put hadoop fs -copyFromLocal <br>- from hdfs to local copyToLocal get what if we have to move a file from one location in hdfs to other other location in hdfs<br>- cp (copy from one location in hdfs to other location in hdfs) <br>- mv (move from one location in hdfs to other location in hdfs)<br>- hadoop fs -df -h /user/itv005857 (diskfree)<br>- hdfs fsck datanew/biglog.txt -files -blocks -locations (file system check and which locations are each blocks of files kept)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff095acff6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stuff I am learning]]></title>
            <link>https://medium.com/@srbsoni/stuff-i-am-learning-c050d38ac466?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c050d38ac466</guid>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 05:49:51 GMT</pubDate>
            <atom:updated>2026-09-06T18:22:54.084Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuing from <a href="https://medium.com/@srbsoni/stuff-i-am-learning-f0c26ef5c317">basics of big data</a></p><p>Now that we have understood about data node and name node, there is something called as <strong>“Gateway node”</strong>, which works like entry point to entire node (worker nodes &amp; master nodes)</p><blockquote><strong>Linux commands</strong></blockquote><blockquote>pwd --&gt; to access my present working directoy<br>whoami --&gt; details about the username login</blockquote><blockquote>- Linux follows a tree like structure, everything starts with the “root”<br>root directory (top most directory) is denoted by <strong>“/”</strong> and any other folder will be inside this directory</blockquote><blockquote><strong>“cd ” command — to change directory <br></strong>- <strong>“cd ~”</strong> to go the home directory<br>- <strong>“cd ..” </strong>will take to the parent directory<br>- <strong>“cd -”</strong> will take to the previous directory<br>- <strong>“cd .” </strong>will keep in the present directory<br>- <strong>“clear”</strong> clear screen<br>- Let’s say we are in “/data/trend” and we want to go another directory which is underdata say “retail”, then we can use <strong>“cd ../retail”</strong></blockquote><blockquote><strong>absolute path </strong>— gives the complete path from root directory so in above example <strong>“cd /data/retail/” is the complete path</strong><br><strong>relative path — </strong>gives the path relative to the current directory, say we are in “/data/trend/” and we need to go to “/data/retail/” then <strong>“cd ../retail” is the relative path</strong></blockquote><blockquote><strong>“ls ” command — listing files and directories<br></strong>blue colour indicates directories (or “d” at the start)<br>green colour indicates executables<br>black colur denotes normal files (or “-” at the start)</blockquote><blockquote>- <strong>“ls -l”</strong> long listing, details of each file and directory in alphabateical order<br>- <strong>“ls -lr”</strong> long listing, details of each file and directory in reverse alphabateical order<br>- <strong>“ls -lt” </strong>lists the newest file on top and then files in <strong>descending order of creation date</strong><br>-<strong>“ls -ltr” </strong>lists the oldest file on top and then files in <strong>ascending order of creation date (r → reverse order)<br>- “ls -lR” </strong>will recursively print all the directories and files<br>- <strong>“ls -l &lt;absolute path of the directory&gt;” </strong>will list all the files of directory listed in path<br>- <strong>“ls -a” </strong>to see all the hidden files (starts with “.”) <br>- <strong>“ls -aR /ls -Ra/ ls -R -a/ ls -a -R” </strong>to recursively see all the hidden files (starts with “.”)<br>- <strong>“ls -latR”</strong> — will list (l), hidden files (a), newest file first (t), recursive print (R)</blockquote><blockquote>- <strong>“touch file1”</strong> — to create an empty file named “file1”<br>- “<strong>chmod” — change permission<br></strong>Permissions available — r → read (4), w → write (2), x → execute (1)<br>for example “dr-xr-xr-x” denotes: <br>- <strong>d</strong> → <strong>d</strong>irectory, <strong>xr</strong> → <strong>r</strong>ead &amp; execute permission for <strong>owner</strong>, xr → <strong>r</strong>ead &amp; execute permission for <strong>group</strong>, <strong>x → </strong>execute permissions for <strong>others<br>- “chmod 777 file1” → rwx rwx rwx for file 1<br>- “mkdir” is to create a new directory<br>mkdir dir1 dir2 dir3 → </strong>single command to make multiple new directories<br>- <strong>“rmdir” </strong>is to delete a empty directory, if directory is not empty then it will throw an error<br>- <strong>“rm-R”</strong>: to delete a directory, we need to remove it recursively<br>- <strong>“cp”</strong> : to copy files or directories (cp file1 file2, cp file1 dir1, cp -R dir1 dir2, copies dir 1 to dir with all files and structure)<br>- <strong>“mv”</strong> : to move a file from one directory to another (Cut Paste) or to rename a file <br>- <strong>“vi”</strong> : command to create a file with some content, <br><strong>press i</strong> and go to insert mode →write the content → <strong>esc</strong> → exit insert mode → <strong>shift : →press w</strong> to save → <strong>press q t</strong>o quit <br>- <strong>“cat”</strong> : command to see the contents of the file <br>- <strong>“cat &gt; filename”</strong> : another way <strong>to create a file with content</strong>, content can be after executing this command and press “<strong>ctrl d” </strong>to save the file <br>- merge multiple files to one file: <strong>cat file1 file2 &gt;&gt; mergedfile</strong><br>- <strong>“head”</strong> : To display the first 10 lines of a file<br>- <strong>“tail”</strong> : To display the last 10 lines of a file<br>- <strong>“du”: disk usage</strong>: It is used to display the amount of disk space used by files and directories <br>- <strong>“du -h” :</strong>diskusage in human readable format<br>- <strong>“grep”</strong> : It searches for lines which contains a search pattern: <strong>grep test * →</strong>searches “test” in al the files<br>- <strong>“exit”</strong> : To close the terminal window and end the execution of shell script</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c050d38ac466" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stuff I am learning]]></title>
            <link>https://medium.com/@srbsoni/stuff-i-am-learning-f0c26ef5c317?source=rss-7f00fba8b20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0c26ef5c317</guid>
            <dc:creator><![CDATA[Saurabh Soni]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 07:29:12 GMT</pubDate>
            <atom:updated>2026-09-01T07:29:12.545Z</atom:updated>
            <content:encoded><![CDATA[<p>Resources : Compute aka CPU, Memory aka RAM, Storage aka Hard disk<br><strong>Monolythic systems </strong>—<br>- 1 System, say a laptop<br>- Compute — 4 cores, Memory — 8GB RAM, Storage — 1 TB<br>- Drawback: Say X resources give Y performances but <br> 2X resources doesn’t necissarily means 2Y performance: <strong>this is verical scaling</strong> (increasing power of 1 machine)<br> <strong>So not a scalable system</strong></p><blockquote><strong>Distributed systems — <br></strong>- Cluster of monolythoc machine<br>- say 5 node cluster, i.e. 5 laptops with config of 4 cores, 8 GB ram, 1 TB storage<br>- To handle the data, you add more machines or nodes, so 2X resources will give 2Y performance: <strong>this is horizontal scaling<br>Good big data architecture: Scalable system</strong></blockquote><blockquote>So to design a good big data system following should be thought of<br>1. Distributed Storage<br>2. Distributed Compute/processing<br>3. Scalability</blockquote><p>Alright! Let’s marry the above discussed pointers with a traditional term HADOOP. Hadoop is an ecosystem to solve big data problem. It has three component (HDFS, Mapreduce, YARN)</p><blockquote>1. Distributed Storage — HDFS (Hadoop distributed file system)<br>2. Distributed Compute/processing — Mapreduce<br>3. Scalability — YARN (yet another resource negotiator or a resource manager)</blockquote><p>Traditionally there were/are multiple component of Hadoop ecosystem mapped with current technologies:<br>1. Sqoop — For data ingestion &amp; export (<strong>Azure Datafactory</strong>)<br>2. pig — scripting language for cleaning the data (obselete now)<br>3. Hive — a sql kind of interface to query the data (still used)<br>4. Oozie — workflow scheduler (<strong>Azure Datafactory</strong>)<br>5. HBase — noSQL database (<strong>CosmosDB)</strong></p><p>Challenges with Hadoop — need to learn a lot of components and it’s mostly an on-premise setup</p><p>Alright, let’s learn some more theory/fundamentals</p><blockquote><strong>Database vs Datawarehouse vs DataLake</strong> <br><strong>Database:<br></strong>- <strong>For OLTP use cases</strong> (online transactional processing): Holds transactional data for day to day operations eg. amazon transactional data, banking trasnactional data<br>- Can only <strong>store structured data<br>- </strong>Data is <strong>more recent</strong> (historical data storage is very expensive)<br>- <strong>Schema on write</strong>: while writing/inserting the data it validates table schema created <br>- <strong>Cost to store data is high</strong><br>- MySQL, Oracle are some examples</blockquote><blockquote><strong>Datawarehouse:<br>- For OLAP use cases </strong>(online analytical processing): analytical purposes for insights using historical data<br>- if DB is used for analytical purposes, DBs storing day to day operations will become slow. So DB data is transferred to DWH for analysis, also <strong>data from multiple DBs, sources can be stored in DWH</strong><br>- Can only <strong>store structured data<br>- Schema on write</strong>: while writing/inserting the data it validates table schema created<br>- <strong>Storage cost is lesser than Databases <br>- </strong>Follows ETLprocess <strong>Extract</strong> the data → <strong>Transform</strong> the data (eg. change date format) →<strong>Load</strong> the data. Transformation before loading <strong>reduces flexibility</strong><br>- Teradata is one example</blockquote><blockquote><strong>Datalake:<br>- </strong>For<strong> OLAP use cases<br>- </strong>Data is present in <strong>it’s raw format</strong>, structured and/or unstructured, say a log file in JSON format<br>- Follows ELT process — <strong>Extract → Load → then Transform </strong>(transformation is thought while using the data, so <strong>flexibility is high</strong>)<strong><br>- </strong>Data structure or transformation can be thought while using the data and in a different format by different use cases<br>- Very cost effective (lesser than DWH)<br>- Follows <strong>Schema on Read</strong>, while reading the file (say employee_detail.csv), sturcuture of the data and data are stored seperately, while reading the data structures is imposed<br>- Amazon S3, Azure Datalake are some examples</blockquote><p>Alright! Let’s start with some basics of <strong>Data Engg. flow</strong></p><blockquote>A typical data engg flow would be as follows:</blockquote><blockquote>Multiple Source → Data ingestion → DataLake → Processing/transformation → Serving Layer → BI tools</blockquote><blockquote><strong>Hadoop:<br></strong>MySQL DB → Sqoop (import) → HDFS (Datalake) → MapReduce or Spark → Hive (DWH) or Hbase (NoSQL)</blockquote><blockquote><strong>Azure Cloud<br></strong>Multiple Sources → Azure DataFactory (ADF) → Azure DataLake System Gen2 → Azure Datafactory or Synapse → Azure SQL or CosmosDB (NoSQL)</blockquote><blockquote><strong>AWS Cloud</strong> <br>Multiple Sources → AWS Glue → Amazon S3 → AWS Databricks/Athena/Redshift → AWS RDS or DynamoDB (NoSQL)</blockquote><p>Now, let’s learn another concept in <strong>Computation or Processing: ServerLess vs ServerFul</strong></p><p>In AWS Redshift or Athena both can be used for processing but <strong>when to use Redshift and when to use Athena?</strong><br>- Now <strong>Athena is Serverless </strong>which means Athena charges you based on amount of data scanned in S3 (say $5 per 1TB data scanned) but does have any dedicated cluster but on <strong>shared pool of resources</strong> for processing<br>while and performance is not <strong>guranteed</strong><em> (meaning if a query is running 2 mins today, doesn’t mean it will take just mins tomorrow)</em><br>- For Redshift, you turn on a <strong>dedicated cluster</strong>, but even when you are not using the resources you are paying for it but you can guaranteed performance</p><blockquote>So <strong>Serverless</strong> should be used when:<br>1. <strong>Only 1 or 2 query at a dedicated time</strong> say everyday<br>2. Query <strong>runtime is not a concern</strong><br>For above 2 requirements turning on a dedicated cluster is not required <br>Advantages: With right optmization of data scan, cost will be less</blockquote><blockquote>But you need <strong>multiple processing queries everyday and performance is of utmost concern</strong> then a dedicated resources will be required and that’s when <strong>“Serverful” </strong>is used</blockquote><p>Let’s learn HDFS in detail</p><blockquote>- HDFS is part of Hadoop which is used for storage and it follows master and slave methodology<br>- <strong>Data nodes</strong> (containing actual data) are the slave nodes, and <strong>Name node </strong>(containing the metadata of the data nodes) is the master node<br>- Data nodes store the data in blocks of 128MB<br>- Name node contains the details of the blocks stored in data node<br>- Now when client requests the data, the request goes to Name node and then name nodes guides from which data nodes should the data be fetched<br>- To prevent the <strong>data loss due to failure of data node, each block is stores in multiple other nodes. By default replcation factor is 3</strong>, that means the blocks of each data node is stored in 3 other data nodes <br>- If actual name node fails, there is a secondary name node that keeps the data of actual name node<br>- And if data nodes are increased then name node can also be scaled, this concept is called <strong>“Name Node Federation”<br>- </strong>Another new term <strong>“Rack”</strong> — Rack is group of servers (data nodes) which is kept in a geographic location, which is far away from other geographies<br>- Now to prevent data loss from data nodes due to a calamity in one geography, other 3 copies of data blocks are kept in other geogrpahies</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0c26ef5c317" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>