<?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 El Amin on Medium]]></title>
        <description><![CDATA[Stories by El Amin on Medium]]></description>
        <link>https://medium.com/@dlamine9?source=rss-b5c7b133cbe3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RU1jtROZO1tPzpTgtHxfKQ@2x.jpeg</url>
            <title>Stories by El Amin on Medium</title>
            <link>https://medium.com/@dlamine9?source=rss-b5c7b133cbe3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:27:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dlamine9/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[PySpark for SQL Professionals: Same Question, New Execution Model | Clouds4Tech]]></title>
            <link>https://medium.com/@dlamine9/pyspark-for-sql-professionals-same-question-new-execution-model-clouds4tech-3c118ef98442?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c118ef98442</guid>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 00:48:59 GMT</pubDate>
            <atom:updated>2026-09-22T00:48:59.183Z</atom:updated>
            <content:encoded><![CDATA[<p>You can read a GROUP BY query in seconds. Then you open a PySpark notebook, see a chain of dots and parentheses, and suddenly feel like a beginner again.</p><p>Start with the question, not the punctuation. Which rows belong? What does one output row represent? Which measure are we calculating? Your SQL judgment still does useful work here.</p><p>The part worth slowing down for is execution. A chain of DataFrame transformations describes work. An action asks Spark to evaluate it. The last line of Python is not necessarily the moment the data was processed.</p><p>This is the paired-query milestone from the <a href="https://clouds4tech.com/blog/sql-server-to-azure-databricks-data-engineer-roadmap">four-stage SQL Server-to-Databricks roadmap</a>. We will keep it small enough to check every row.</p><h3>Start with six rows, not a missing table</h3><p>The question: how many completed orders has each customer placed since January 1, 2026, and what is their total net amount? The output grain is one row per customer. These six fictional orders include a cancelled order, an older order, and a null amount so the edge cases are visible.</p><p>In a Python notebook attached to suitable Databricks compute, create the sample below. It uses an explicit decimal type for amounts and does not read a customer database or write a persistent table. The Spark session named spark is supplied by the notebook.</p><pre>from datetime import date from decimal import Decimal from pyspark.sql import functions as F rows = [ (1001, 101, &quot;COMPLETE&quot;, date(2026, 1, 2), Decimal(&quot;125.00&quot;)), (1002, 101, &quot;COMPLETE&quot;, date(2026, 1, 3), Decimal(&quot;50.00&quot;)), (1003, 102, &quot;COMPLETE&quot;, date(2026, 1, 4), Decimal(&quot;40.00&quot;)), (1004, 102, &quot;CANCELLED&quot;, date(2026, 1, 4), Decimal(&quot;90.00&quot;)), (1005, 103, &quot;COMPLETE&quot;, date(2025, 12, 31), Decimal(&quot;10.00&quot;)), (1006, 102, &quot;COMPLETE&quot;, date(2026, 1, 5), None), ] orders = spark.createDataFrame( rows, &quot;order_id INT, customer_id INT, order_status STRING, &quot; &quot;order_date DATE, net_amount DECIMAL(12,2)&quot;, ) orders.createOrReplaceTempView(&quot;c4t_pyspark_orders_demo&quot;)</pre><p>Use a disposable notebook session. The last line creates or replaces only the session-local demonstration view named c4t_pyspark_orders_demo. The examples are instructional: no Azure Databricks execution or performance measurement is claimed here.</p><h3>Translate the business question</h3><p>For the SQL Server version, imagine the same six rows and types in a synthetic dbo.orders table. This is T-SQL; CONVERT with style 112 makes the date boundary explicit.</p><pre>-- T-SQL: SQL Server, using synthetic dbo.orders SELECT customer_id, COUNT(*) AS order_count, SUM(net_amount) AS net_revenue FROM dbo.orders WHERE order_status = &#39;COMPLETE&#39; AND order_date &gt;= CONVERT(date, &#39;20260101&#39;, 112) GROUP BY customer_id;</pre><p>For a comparison inside the Databricks notebook, use Spark SQL against the temporary view we just created. The DATE literal below belongs to Spark SQL, not T-SQL.</p><pre>-- Spark SQL: run in a Databricks SQL cell SELECT customer_id, COUNT(*) AS order_count, SUM(net_amount) AS net_revenue FROM c4t_pyspark_orders_demo WHERE order_status = &#39;COMPLETE&#39; AND order_date &gt;= DATE &#39;2026-01-01&#39; GROUP BY customer_id;</pre><p>Here is the same intent using the DataFrame API. Read it as source → predicate → grain → measures.</p><pre>customer_summary = ( orders .filter( (F.col(&quot;order_status&quot;) == &quot;COMPLETE&quot;) &amp; (F.col(&quot;order_date&quot;) &gt;= F.lit(date(2026, 1, 1))) ) .groupBy(&quot;customer_id&quot;) .agg( F.count(&quot;*&quot;).alias(&quot;order_count&quot;), F.sum(&quot;net_amount&quot;).alias(&quot;net_revenue&quot;), ) )</pre><ul><li>WHERE maps to filter(): choose the qualifying rows.</li><li>GROUP BY maps to groupBy(): declare the output grain. groupBy() returns GroupedData; agg() produces the aggregated DataFrame.</li><li>COUNT(*) counts qualifying rows, including the row with a null amount. SUM(net_amount) ignores null amounts; an all-null group would return null, not zero.</li><li>SELECT maps to select() for projection. A CTE can often become a named intermediate DataFrame; that name does not materialize or cache the result.</li></ul><p>For this fixture, expect customer 101 to have 2 orders and 175.00 net revenue; customer 102 has 2 orders and 40.00. The cancelled order and the 2025 order do not qualify. That null amount is a quality question, not permission to assume missing revenue is zero.</p><h3>Find the action boundary</h3><p>The filter and aggregation describe the calculation. Ask to display results and Spark evaluates the work needed to produce them. The diagram is a teaching illustration, not a recording of a running cluster.</p><p>Use explain(mode=&quot;formatted&quot;) to inspect the physical plan outline and node details. Use show() deliberately to request rows. Explaining a plan does not prove an execution time, a cost, or that the result is correct.</p><pre>customer_summary.explain(mode=&quot;formatted&quot;) customer_summary.orderBy(&quot;customer_id&quot;).show(10, truncate=False)</pre><p>Do not read show(10) as “Spark only processes ten source rows.” Filtering, grouping, and sorting can require much more work. An action can launch jobs; do not assume one action always means exactly one job.</p><p>Be careful with collect(): it loads the complete result into driver memory. It is reasonable for this known tiny test fixture, not a default way to inspect an unknown production DataFrame. Repeated actions can also recompute work unless reuse or caching applies.</p><h3>Check the result before tuning the plan</h3><p>A green notebook cell is not a reconciliation. For these six rows, check exact keys, counts, and decimal totals. The assertion below deliberately collects a result whose maximum size is bounded by this tiny synthetic fixture.</p><pre>actual = [tuple(row) for row in customer_summary.orderBy(&quot;customer_id&quot;).collect()] expected = [ (101, 2, Decimal(&quot;175.00&quot;)), (102, 2, Decimal(&quot;40.00&quot;)), ] assert actual == expected, (actual, expected)</pre><p>The <a href="https://clouds4tech.com/examples/pyspark-for-sql-professionals.py">downloadable six-row Python demo</a> also compares the Spark SQL result with the DataFrame result, exercises an empty input, and checks an all-null revenue group. Those assertions are intended runtime checks, not evidence that this article has run in your workspace.</p><p>Then change one assumption: add a duplicate order ID, a null customer ID, or a differently cased status. Decide what the business rule should be before changing code. SQL Server collation and Spark string-comparison behavior can differ, so test text matching rather than assuming that familiar-looking predicates behave identically.</p><p>Keep checks at the right grain. A null check on the grouped summary counts customer groups, not invalid source orders. Validate source keys and amounts before aggregation when you need a row-level reject count.</p><h3>One thing to try today</h3><p>Write down a familiar aggregation without copying customer or employer code. Build a tiny fictional input with one awkward row. Express the query in SQL and PySpark, state the output grain, and check the expected result before looking for a faster plan.</p><p>You are not starting over. You are applying the same habit-understand the data, then prove the result-to a different engine.</p><p>Put the exercise into a learning plan with the free <a href="https://clouds4tech.com/resources/sql-to-databricks-90-day-roadmap">SQL Server to Databricks 90-Day Roadmap</a>. For a guided source-to-Delta build, see the <a href="https://clouds4tech.com/workshops/sql-to-delta-medallion-pipeline">SQL-to-Delta Medallion Pipeline workshop</a> for the current schedule and registration details.</p><h3>Sources and example scope</h3><p>Sources reviewed September 15, 2026. The comparisons and learning sequence are Clouds4Tech teaching guidance. All data is fictional. The examples have not been executed in Azure Databricks or SQL Server for this article; expected results are fixture calculations, not captured platform output. Runtime plans and performance depend on your environment.</p><p>Your next practical checkpoint</p><h3>Build one query you can explain.</h3><p>Use the free 90-day roadmap to turn SQL experience into small, testable Databricks milestones.</p><p><a href="https://clouds4tech.com/resources/sql-to-databricks-90-day-roadmap">Get the free roadmap</a></p><p><em>Originally published at </em><a href="https://clouds4tech.com/blog/pyspark-for-sql-professionals"><em>https://clouds4tech.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c118ef98442" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Already Know More Databricks Than You Think: A 4-Stage Roadmap for SQL Server Professionals |…]]></title>
            <link>https://medium.com/@dlamine9/you-already-know-more-databricks-than-you-think-a-4-stage-roadmap-for-sql-server-professionals-29e7968889a0?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/29e7968889a0</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 16:28:43 GMT</pubDate>
            <atom:updated>2026-09-14T16:48:58.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>You Already Know More Databricks Than You Think: A 4-Stage Roadmap for SQL Server Professionals | Clouds4Tech</h3><figure><img alt="Four-stage roadmap from SQL Server foundations through PySpark and Delta Lake to governed, deployable Azure Databricks pipelines." src="https://cdn-images-1.medium.com/max/1024/1*G3Mv3fIUuDEAP9gFQvPM7Q.png" /></figure><p>Open Databricks for the first time and it feels like someone renamed everything you know.</p><p>Clusters instead of SQL Server instances. Catalogs and schemas instead of databases and schemas. Notebooks and jobs instead of stored procedures and SQL Agent.</p><p>That comparison helps for about five minutes. Then it gets dangerous.</p><p>The real advantage you bring from SQL Server is not vocabulary. It is the habit of asking operational questions: What happens on the second run? How do I reconcile the source and target? Who owns access? What evidence will I have when this fails at 2:00 AM?</p><p>Databricks changes the operating model. It does not make those questions disappear.</p><p>Here is the four-stage path I would use to turn SQL Server experience into a Databricks project you can build, rerun, and explain.</p><p>If you are still deciding what transfers from SQL Server and what requires a new mental model, start with the <a href="https://clouds4tech.com/blog/sql-server-dba-to-azure-databricks-guide">broader SQL Server DBA-to-Databricks transition guide</a>. This field guide starts one step later: with the four artifacts that prove you can build and operate the transition.</p><h3>Stage 1: Translate responsibilities, not product names</h3><p>A SQL Server database is an engine, storage system, security boundary, and operational unit bundled together. In a lakehouse, compute and storage are more explicitly separated. Apache Spark performs distributed processing, Delta Lake adds transactional table capabilities, and Unity Catalog governs data and AI assets.</p><p>Use analogies as a bridge. Then test where they break:</p><ul><li>A Unity Catalog three-part name resembles database.schema.object , but catalog design is also about environment, domain, ownership, and access isolation.</li><li>A Delta table supports familiar SQL operations, but its files and transaction log live in cloud storage rather than SQL Server data files.</li><li>A Lakeflow Job resembles an orchestrated SQL Agent workflow, but tasks can span notebooks, pipelines, SQL, and other workloads.</li></ul><p>Your first proof should be small: create a development catalog and schema, write one Delta table, query it with SQL, inspect its history, and document who should be allowed to read and modify it.</p><figure><img alt="SQL Server responsibilities mapped to Spark compute, Delta Lake storage, Unity Catalog governance, and Lakeflow operations without implying direct architectural equivalence." src="https://cdn-images-1.medium.com/max/1024/1*NxTPjcMm-bJk5J8x7COzOA.png" /></figure><h3>Stage 2: Start with a query you already understand</h3><p>Start with the work you already recognize: select columns, filter rows, join datasets, aggregate measures, handle nulls, and validate types. Express each operation once in SQL and once with the PySpark DataFrame API.</p><pre>SELECT customer_id, SUM(net_amount) AS lifetime_value FROM retail_demo.silver.orders WHERE order_status = &#39;COMPLETE&#39; GROUP BY customer_id;</pre><pre>from pyspark.sql import functions as F customer_value = ( spark.table(&quot;retail_demo.silver.orders&quot;) .filter(F.col(&quot;order_status&quot;) == &quot;COMPLETE&quot;) .groupBy(&quot;customer_id&quot;) .agg(F.sum(&quot;net_amount&quot;).alias(&quot;lifetime_value&quot;)) )</pre><p>Same business question. Different execution model.</p><p>DataFrame transformations are lazily evaluated. Partitions influence the work. An action such as a write, count, or display triggers computation. Do not read the Python from top to bottom and assume Spark executed each line as it appeared.</p><p>Build five SQL/PySpark pairs over synthetic data. For one of them, run and describe the plan in plain English. If you cannot explain the plan, you do not understand the transformation yet.</p><h3>Stage 3: Make the second run part of the demo</h3><p>Choose a non-sensitive sample domain such as orders and customers. Land source-aligned data in bronze, validate types and keys in silver, and produce one business-facing gold table. Add a repeatable load strategy, rejected-record handling, and a reconciliation query.</p><p>For a first portfolio pipeline, prove these operating behaviors:</p><ul><li>Rerunning the same batch does not silently duplicate rows.</li><li>Invalid records are visible and explainable.</li><li>Source and target row counts can be reconciled.</li><li>The pipeline records when and from which batch each row arrived.</li><li>A failed transformation can be corrected and rerun.</li></ul><p>I would not trust a production ETL job because it ran once. A portfolio pipeline should not get a lower standard.</p><p>Demonstrate a full load and a second incremental load. Show exactly how you identified inserts, updates, rejects, and unchanged rows. The second run is where the engineering starts.</p><figure><img alt="Two-batch pipeline animation showing duplicate rows from a naive append and a reconciled result from a rerun-safe design." src="https://cdn-images-1.medium.com/max/960/1*_-HfYlabdP2JihbmiLffqQ.gif" /></figure><h3>Stage 4: Move beyond the notebook screenshot</h3><p>A notebook screenshot proves exploration. A data-engineering portfolio project should also prove repeatability. Put code under Git, separate configuration from logic, add tests, and describe Databricks resources with Declarative Automation Bundles-the current name for the capability formerly called Databricks Asset Bundles.</p><p>Use Unity Catalog permissions and lineage to show that governance is part of the design, not an appendix. Add a runbook covering failure, replay, monitoring, data-quality thresholds, and cost boundaries.</p><p>Validate the bundle, deploy to a development target, run the pipeline, and capture evidence without exposing tenant names, credentials, or proprietary data.</p><p>Bundle validation is useful evidence. It is not proof that the project is production-ready. Say exactly what you tested and where you tested it.</p><h3>The four artifacts I would build</h3><ol><li>A governed Delta table with a documented owner and access boundary.</li><li>Five paired SQL/PySpark transformations, including one explained Spark plan.</li><li>A two-batch SQL-to-Delta pipeline with rejects, reconciliation, and rerun evidence.</li><li>A Git-based project with tests, a bundle, a runbook, and a sanitized development deployment.</li></ol><p>One complete system tells me more than ten disconnected notebooks. Build the smallest system that lets you prove behavior, then use its gaps to decide what to learn next.</p><h3>One takeaway</h3><p>Do not introduce yourself to Databricks as a complete beginner. Bring your SQL Server judgment with you. Just be disciplined about where the analogy stops.</p><p>Translate the responsibility. Build the artifact. Run it twice. Show the evidence.</p><p>Download the free <a href="https://clouds4tech.com/resources/sql-to-databricks-90-day-roadmap">SQL Server to Databricks 90-Day Roadmap</a>, then register for the free <a href="https://clouds4tech.com/workshops/sql-to-delta-medallion-pipeline">Build Your First SQL-to-Delta Medallion Pipeline workshop</a>. The live 90-minute workshop is scheduled for October 10, 2026 at 10:00 AM Eastern.</p><h3>Sources</h3><p>The product facts above were reviewed on September 13, 2026. The four-stage sequence and SQL Server analogies are Clouds4Tech teaching guidance, not a Microsoft-prescribed timeline.</p><p>Build the transition deliberately</p><h3>Use the complete 90-day roadmap.</h3><p>Turn each stage into a small, reviewable portfolio milestone with practical SQL-to-lakehouse checkpoints.</p><p><a href="https://clouds4tech.com/resources/sql-to-databricks-90-day-roadmap">Get the free roadmap</a></p><p><em>Originally published at </em><a href="https://clouds4tech.com/blog/sql-server-to-azure-databricks-data-engineer-roadmap"><em>https://clouds4tech.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29e7968889a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ultimate Guide: Introduction to Spark DataFrames + Basic PySpark Operations in Databricks]]></title>
            <link>https://medium.com/@dlamine9/ultimate-guide-introduction-to-spark-dataframes-basic-pyspark-operations-in-databricks-b170f12cc93b?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b170f12cc93b</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark-dataframes]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 20:24:05 GMT</pubDate>
            <atom:updated>2025-06-26T20:24:05.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tN90UOsFtUsUN_7-RQfOWg.png" /></figure><p>Introduction to Spark DataFrames, Show basic DataFrame operations (select, filter, join) in PySpark within Databricks — Master PySpark DataFrame operations like select(), filter(), and join() through hands-on examples using Databricks notebooks.</p><h3>What Are Spark DataFrames?</h3><p>A <strong>Spark DataFrame</strong> is a distributed collection of data organized into named columns, conceptually similar to a table in a relational database or a Pandas DataFrame in Python. Spark DataFrames provide an abstraction over <strong>Resilient Distributed Datasets (RDDs)</strong>, allowing you to work with structured data using high-level operations.</p><h3>Structured Data Abstraction in Spark</h3><p>The key strength of DataFrames lies in their ability to define a <strong>schema</strong>, giving structure and meaning to the data. This schema allows for optimization during execution using Spark’s Catalyst optimizer and Tungsten execution engine.</p><h3>Evolution from RDDs to DataFrames</h3><p>While RDDs are powerful and flexible, they require more code and offer fewer optimizations. DataFrames abstract away much of this complexity and bring SQL-like querying capabilities into the PySpark ecosystem.</p><h3>Why Use Spark DataFrames in PySpark?</h3><h3>Performance Benefits</h3><p>Spark DataFrames are optimized for performance. By operating on structured data, Spark can apply advanced optimizations like predicate pushdown, vectorization, and query caching.</p><h3>Compatibility with Spark SQL</h3><p>You can seamlessly run SQL queries on DataFrames and register them as temporary views in Spark. This dual-language capability (Python + SQL) is a game changer.</p><h3>Distributed Processing</h3><p>DataFrames operate on data in a distributed fashion, meaning you can process huge datasets that don’t fit into memory on a single machine — without writing low-level MapReduce logic.</p><h3>Setting Up PySpark in Databricks</h3><p>Before we begin working with DataFrames, let’s get the environment ready in <strong>Databricks</strong>.</p><h3>Creating a Databricks Notebook</h3><ol><li>Log into your Databricks workspace.</li><li>Create a new notebook and select the cluster.</li><li>Choose <strong>Python</strong> as the default language.</li></ol><h3>Initializing a SparkSession</h3><pre>from pyspark.sql import SparkSession</pre><pre>spark = SparkSession.builder.appName(&quot;DataFrameDemo&quot;).getOrCreate()</pre><p>This is the entry point for all DataFrame operations in PySpark.</p><h3>Loading Sample Data</h3><p>Databricks provides many sample datasets, or you can upload your own .csv, .json, or .parquet files for experimentation.</p><h3>Creating a DataFrame in PySpark</h3><h3>Using Lists and Schemas</h3><pre>data = [(&quot;Alice&quot;, 30), (&quot;Bob&quot;, 45), (&quot;Cathy&quot;, 29)]<br>columns = [&quot;Name&quot;, &quot;Age&quot;]</pre><pre>df = spark.createDataFrame(data, columns)<br>df.show()</pre><h3>Reading from CSV/JSON/Parquet</h3><pre>df_csv = spark.read.csv(&quot;/FileStore/data/sales.csv&quot;, header=True, inferSchema=True)<br>df_json = spark.read.json(&quot;/FileStore/data/products.json&quot;)</pre><p>Each of these methods supports various schema and read options.</p><h3>Basic DataFrame Operations Overview</h3><p>The <strong>three most essential operations</strong> in any Spark DataFrame are:</p><ul><li>select(): to pick columns</li><li>filter() or where(): to narrow down data</li><li>join(): to combine datasets</li></ul><h3>Using select() to Extract Columns</h3><h3>Syntax and Example</h3><pre>df.select(&quot;Name&quot;, &quot;Age&quot;).show()</pre><p>You can also rename or compute columns on the fly:</p><pre>from pyspark.sql.functions import col</pre><pre>df.select(col(&quot;Age&quot;) * 2).show()</pre><h3>Selecting Nested Fields</h3><p>In complex datasets (e.g., JSON), fields may be nested. Use dot notation to access nested fields.</p><h3>Filtering Data with filter() and where()</h3><h3>Using Logical Conditions</h3><pre>df.filter(col(&quot;Age&quot;) &gt; 30).show()</pre><h3>Filter by String or Null</h3><pre>df.filter(col(&quot;Name&quot;) == &quot;Bob&quot;).show()<br>df.filter(col(&quot;Age&quot;).isNull()).show()</pre><h3>Using where()</h3><p>where() is an alias for filter(), and both can be used interchangeably.</p><h3>Combining DataFrames Using join()</h3><h3>Types of Joins</h3><pre>df1.join(df2, df1[&quot;id&quot;] == df2[&quot;id&quot;], &quot;inner&quot;).show()</pre><p>Available join types include: inner, left, right, outer.</p><h3>Join Conditions and Aliases</h3><pre>df1.alias(&quot;a&quot;).join(df2.alias(&quot;b&quot;), col(&quot;a.id&quot;) == col(&quot;b.id&quot;)).select(&quot;a.name&quot;, &quot;b.score&quot;).show()</pre><p>Using aliases avoids column ambiguity and keeps queries readable.</p><h3>Chaining Multiple Operations</h3><p>You can chain multiple DataFrame transformations:</p><pre>df.select(&quot;Name&quot;, &quot;Age&quot;).filter(col(&quot;Age&quot;) &gt; 30).show()</pre><p>This method keeps your code clean and efficient.</p><h3>Visualizing Data in Databricks</h3><h3>Using Built-In Visualizations</h3><p>After executing df.display(), click the <strong>&quot;Visualization&quot;</strong> tab to render charts (bar, pie, line, etc.).</p><h3>Display() Function</h3><pre>display(df)</pre><p>Databricks automatically detects data types and suggests visual formats.</p><h3>Best Practices for Working with DataFrames in PySpark</h3><p>Working with large-scale data requires not just functionality, but also <strong>efficiency</strong> and <strong>readability</strong>. These best practices will help you write scalable and maintainable PySpark code.</p><h3>Cache When Necessary</h3><p>If you’re going to use the same DataFrame multiple times in your workflow:</p><pre>python<br>CopyEdit<br>df.cache()<br>df.count()  # Action to trigger caching</pre><p>Caching stores the DataFrame in memory across the cluster, reducing execution time for repeated use.</p><h3>Avoid Wide Transformations</h3><p>Wide transformations like groupBy() and join() cause <strong>data shuffling</strong> across the network. Minimize their use or <strong>filter and reduce data size before</strong> applying them.</p><h3>Use Column Functions Efficiently</h3><p>Instead of using plain Python functions, stick with PySpark’s built-in functions like col(), when(), isNull(), etc., which are <strong>optimized for distributed computation</strong>.</p><h3>Common Errors and Debugging Tips</h3><h3>Schema Mismatch</h3><p>A common issue is schema misalignment. Use df.printSchema() to inspect column types before operations.</p><h3>NullPointer Issues</h3><p>If your data contains nulls, use:</p><pre>python<br>CopyEdit<br>df.na.fill(&quot;Unknown&quot;)  # For strings<br>df.na.drop()           # To remove rows with nulls</pre><h3>Join Key Errors</h3><p>Ensure that your join keys are <strong>not null</strong> and have the <strong>same data type</strong>. Mismatches lead to empty results or silent errors.</p><h3>When to Use DataFrames Over RDDs</h3><h3>Performance Tradeoffs</h3><p>Use DataFrames when:</p><ul><li>Your data is structured</li><li>You want better optimization</li><li>You plan to use SQL queries</li></ul><p>Use RDDs if:</p><ul><li>Your data is unstructured</li><li>You need low-level transformation logic</li></ul><h3>SQL Compatibility</h3><p>DataFrames can be registered as SQL views:</p><pre>python<br>CopyEdit<br>df.createOrReplaceTempView(&quot;people&quot;)<br>spark.sql(&quot;SELECT * FROM people WHERE Age &gt; 30&quot;).show()</pre><h3>Real-World Example: Analyzing Sales Data</h3><p>Let’s apply what we’ve learned using a <strong>real dataset</strong>.</p><h3>Loading Sales Data from CSV</h3><pre>python<br>CopyEdit<br>sales_df = spark.read.csv(&quot;/FileStore/data/sales.csv&quot;, header=True, inferSchema=True)</pre><h3>Filtering Data for a Specific Region</h3><pre>python<br>CopyEdit<br>sales_df.filter(col(&quot;Region&quot;) == &quot;West&quot;).show()</pre><h3>Joining with Product Metadata</h3><pre>python<br>CopyEdit<br>products_df = spark.read.csv(&quot;/FileStore/data/products.csv&quot;, header=True, inferSchema=True)<br>combined_df = sales_df.join(products_df, &quot;ProductID&quot;)<br>combined_df.select(&quot;ProductName&quot;, &quot;Revenue&quot;).show()</pre><p>This approach is great for real-time analytics in e-commerce, logistics, or any retail-based domain.</p><h3>Wrapping Up and Next Steps</h3><p>Working with <strong>Spark DataFrames in PySpark within Databricks</strong> offers a powerful, scalable way to process massive datasets interactively. You’ve now seen how to use the foundational operations — select(), filter(), and join()—alongside performance tips and real examples.</p><h3>Next Steps</h3><ul><li>Learn advanced transformations using groupBy, agg, and window functions</li><li>Explore <strong>Delta Lake</strong> for ACID transactions and schema enforcement</li><li>Transition to <strong>Spark Structured Streaming</strong> for real-time analytics</li></ul><h3>FAQs: Spark DataFrames and PySpark Operations in Databricks</h3><h3>Q1: What is the difference between filter() and where() in PySpark?</h3><p>A: Both do the same job — filter rows based on a condition. where() is just an alias for filter().</p><h3>Q2: How do I handle missing values in a DataFrame?</h3><p>A: Use .na.drop() to remove them or .na.fill(value) to fill them with a default.</p><h3>Q3: Can I perform SQL queries on a DataFrame?</h3><p>A: Yes. Register it as a temp view using createOrReplaceTempView() and run SQL using spark.sql().</p><h3>Q4: What kind of joins are supported in PySpark?</h3><p>A: Inner, left, right, outer, semi, and anti joins are all supported.</p><h3>Q5: How do I see the schema of a DataFrame?</h3><p>A: Use df.printSchema().</p><h3>Q6: Can I export the DataFrame result to a file in Databricks?</h3><p>A: Yes. Use df.write.csv(&quot;/path&quot;), df.write.parquet(&quot;/path&quot;), or df.write.json(&quot;/path&quot;).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b170f12cc93b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Delta Lake Clone for Data Backups & Experiments]]></title>
            <link>https://medium.com/@dlamine9/how-to-use-delta-lake-clone-for-data-backups-experiments-d1516cb13fbe?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1516cb13fbe</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[data-versioning]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 18:28:10 GMT</pubDate>
            <atom:updated>2025-04-15T18:28:10.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*314H1wwbHTesn-2Ctqnmdg.jpeg" /></figure><p>Welcome to Day 13 of the 30-Day Databricks Crash Course!<br>Today we’re covering a powerful, underused feature in Delta Lake: cloning tables for fast backups, testing, and sandbox experiments.</p><p>🧠 What Is a Clone in Delta Lake?<br>Delta Lake allows you to create a copy of a table instantly using the CLONE command.<br>It supports two types:<br>✅ Shallow Clone: Fast, storage-efficient copy (shares files)<br>✅ Deep Clone: Full physical copy (good for backups or workspace migrations)</p><p>🔍 Shallow Clone vs Deep Clone</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*P37xFaNRHcf5ZsrDCXyfvA.png" /></figure><p>💡 Shallow = metadata + pointers<br>💡 Deep = actual data files duplicated</p><p>🧪 SQL Syntax Example</p><pre>- Shallow clone<br>CREATE TABLE dev_table_shallow CLONE prod_table;<br> - Deep clone<br>CREATE TABLE backup_table DEEP CLONE prod_table;<br>You can also clone specific versions of a Delta table:sql</pre><p>You can also clone specific <strong>versions</strong> of a Delta table:</p><pre>CREATE TABLE versioned_clone SHALLOW CLONE prod_table VERSION AS OF 25;</pre><p>This is great for <strong>time travel + testing</strong> without affecting production.</p><p>🧰 Real Use Cases</p><h4>Test Changes Safely</h4><p>Clone a prod table → apply schema changes or filters → run tests</p><h4>Create Sandboxes for Analysts</h4><p>Clone once, and let users experiment without touching source</p><h4>Make Auditable Snapshots</h4><p>Deep clone daily or weekly → store for compliance or rollback</p><h4>Instant Feature Branches for ML</h4><p>Clone training data, test new model logic without writing files again</p><h3>⚠️ Limitations to Know</h3><ul><li>Clones only work <strong>within the same workspace and metastore</strong></li><li>Deep clones can <strong>incur significant storage</strong> — use wisely</li><li>You cannot clone <strong>views or non-Delta tables</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1516cb13fbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Concurrent Data Updates in Delta Lake — Explained for Beginners]]></title>
            <link>https://medium.com/@dlamine9/handling-concurrent-data-updates-in-delta-lake-explained-for-beginners-129c4ac2b9e5?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/129c4ac2b9e5</guid>
            <category><![CDATA[data-engineering-101]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 15:25:54 GMT</pubDate>
            <atom:updated>2025-04-14T15:25:54.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling Concurrent Data Updates in Delta Lake — Explained for Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vv9xnEhuyHkfb0hJq08_ew.jpeg" /></figure><p>Welcome to Day 12 of the 30-Day Databricks Crash Course!<br>Today’s focus: How Delta Lake handles concurrent updates.|<br>If you’re running multiple data pipelines or updates on the same table, you might wonder:</p><p><strong>“What happens if two jobs write to the same Delta table at once?”</strong></p><p>Let’s break it down 💡</p><h3>🧠 The Problem: Concurrent Writes</h3><p>In distributed systems (like Spark), multiple jobs can try to update the same data at the same time.<br>If there’s no safety mechanism, one write could silently overwrite another — corrupting your data.<br>That’s where Delta Lake’s built-in protections come in.</p><h3>🛡️ Delta Lake Uses: Optimistic Concurrency Control (OCC)</h3><p>Delta Lake does NOT lock the table during writes.<br>Instead, it uses Optimistic Concurrency Control, which works like this:</p><h4>🧪 OCC in Simple Terms:</h4><p>🔍 Job A and Job B read the Delta table (version X)<br>✍️ Both make changes and prepare to write<br>✅ Job A writes first → creates version X+1<br>❌ Job B now tries to write → Delta sees that it’s stale (still on X), and throws an error<br><em>✅ Only one job wins — others must retry with fresh data</em></p><h3>🔁 Real-Life Example: Two Jobs, One Table</h3><p>Imagine:<br>ETL Job A filters and writes user activity from Region A<br>ETL Job B filters and writes user activity from Region B<br>Both are scheduled to update the same table every 5 minutes</p><p>If both jobs overlap:<br>Job A writes first, version becomes 101<br>Job B, still operating on version 100, tries to write<br>Delta detects the mismatch and raises:</p><pre>ConcurrentModificationException: Transaction conflict detected.​</pre><p>✅ This protects your table from silent overwrites<br>✅ You can catch the error, reload latest data, and retry safely</p><h3>📚 Delta Log: The Secret Behind the Magic</h3><p>Delta maintains a transaction log in the background (_delta_log/)<br>Each write:<br>Records schema, data changes, and metadata<br>Increments the table version</p><p>This log allows:<br>Time travel<br>Full audit history<br>Safe concurrent access</p><h3>✅ How to Handle OCC in Practice</h3><h4>🔄 Best Practice for Conflict Handling</h4><p>Use a try-catch block or job retry mechanism:</p><pre>try: df.write.format(&quot;delta&quot;).mode(&quot;append&quot;).save(&quot;/mnt/delta/events&quot;) <br>except Exception as e: <br>print(&quot;Retrying due to conflict:&quot;, e) <br># Refresh data and retry writ​</pre><p>✅ Add a retry limit to prevent infinite loops<br>✅ Use .merge() or DeltaTable APIs for precise updates</p><h3>🔧 Advanced Tools: DeltaTable API</h3><pre>from delta.tables import DeltaTable <br>delta_tbl = DeltaTable.forPath(spark, &quot;/mnt/delta/events&quot;) <br>delta_tbl.alias(&quot;old&quot;).merge( <br>updates_df.alias(&quot;new&quot;), <br>&quot;old.id = new.id&quot; <br>).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute()​</pre><p>This ensures updates only go where they belong — and uses the same OCC protection under the hood.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129c4ac2b9e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Broadcast Join vs Shuffle Join Explained (With Execution Plan)]]></title>
            <link>https://medium.com/@dlamine9/spark-broadcast-join-vs-shuffle-join-explained-with-execution-plan-7f4a74b8be68?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f4a74b8be68</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark-join-ptimization]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 17:37:25 GMT</pubDate>
            <atom:updated>2025-04-08T17:37:25.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand how broadcast joins work in PySpark and when to use them for faster, more efficient Spark jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nr7nvI6IQqsJIrTMssuI7A.jpeg" /></figure><p>Welcome to <strong>Day 9</strong> of the <strong>30-Day Databricks Crash Course!</strong></p><p>If you’ve ever worked with large joins in Spark and noticed slowdowns, you’re not alone.</p><p>Today, we’ll dive into <strong>broadcast joins</strong> — a powerful way to eliminate expensive shuffles and optimize performance.</p><h3>🔄 What Happens in a Regular Join?</h3><p>When Spark joins two big tables:</p><ul><li>It <strong>shuffles data</strong> across all worker nodes</li><li>It matches keys across partitions</li><li>This causes <strong>network IO, memory pressure, and slow execution</strong></li></ul><h3>⚡ What’s a Broadcast Join?</h3><p>Instead of shuffling both tables, Spark: ✅ <strong>Replicates the smaller dataset to all executors</strong></p><p>✅ Eliminates shuffling the small table</p><p>✅ Enables <strong>faster, more efficient joins</strong></p><pre>from pyspark.sql.functions import broadcast<br><br>df_result = df_large.join(broadcast(df_small), on=&quot;id&quot;, how=&quot;inner&quot;)</pre><h3>📏 How Small Should the Broadcast Table Be?</h3><ul><li>Generally <strong>&lt; 10MB</strong> in size</li><li>Fits in driver memory</li><li>Think <strong>lookup or dimension tables</strong></li></ul><h3>🧪 Practical Example</h3><pre>from pyspark.sql.functions import broadcast<br><br># Small lookup table<br>df_small = spark.createDataFrame([<br>    (&quot;US&quot;, &quot;United States&quot;),<br>    (&quot;CA&quot;, &quot;Canada&quot;),<br>    (&quot;UK&quot;, &quot;United Kingdom&quot;)<br>], [&quot;code&quot;, &quot;country&quot;])<br># Simulated large dataset<br>df_large = spark.range(0, 10000).withColumnRenamed(&quot;id&quot;, &quot;customer_id&quot;)<br>df_large = df_large.withColumn(&quot;country_code&quot;, (df_large.customer_id % 3)<br>                               .cast(&quot;string&quot;)<br>                               .replace({&quot;0&quot;: &quot;US&quot;, &quot;1&quot;: &quot;CA&quot;, &quot;2&quot;: &quot;UK&quot;}))<br># Broadcast join<br>df_joined = df_large.join(<br>    broadcast(df_small),<br>    df_large.country_code == df_small.code,<br>    how=&quot;inner&quot;<br>)<br># Show physical plan<br>df_joined.explain(extended=True)</pre><p>Look for this in the plan:</p><pre>BroadcastHashJoin [country_code], [code], Inner, BuildRight</pre><p>✅ That means Spark applied the <strong>broadcast join optimization</strong>!</p><p>🔁 Broadcast vs Shuffle Join Summary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5w__YRxuJsgyh0c_nYDYrw.png" /></figure><h3>✅ Best Practices</h3><ul><li>Use broadcast() when joining with a <strong>small static table</strong></li><li>Don’t broadcast large datasets — it’ll crash the driver</li><li>Always <strong>verify execution plans</strong> with .explain() or the Spark UI</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f4a74b8be68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Cache vs Persist — The Key to Faster Workflows]]></title>
            <link>https://medium.com/@dlamine9/spark-cache-vs-persist-the-key-to-faster-workflows-04be47fc0dac?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/04be47fc0dac</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 01:28:15 GMT</pubDate>
            <atom:updated>2025-04-08T01:28:15.323Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spark Cache vs Persist — The Key to Faster Workflows</h3><p>Understand the difference between cache() and persist() in Spark. Learn when and why to use each for better performance and memory control in PySpark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RYNXw-lE5V7-AtWL8nMyA.jpeg" /></figure><p>Welcome to <strong>Day 8</strong> of the 30-Day Databricks Crash Course!</p><p>Today, we’re tackling a topic that can <strong>massively improve performance</strong> but is often misunderstood:</p><p><strong>Should you </strong><strong>cache() or </strong><strong>persist() your data in Spark?</strong></p><p>Let’s break it down clearly.</p><h3>🔁 What Does cache() Do?</h3><p>When you call .cache(), Spark <strong>stores your DataFrame in memory</strong> (RAM) on first computation.</p><p>It’s great for <strong>reusing the same dataset multiple times</strong>.</p><h3>✅ Best when:</h3><ul><li>You run <strong>multiple actions</strong> on the same transformed DataFrame</li><li>Your dataset <strong>fits in memory</strong></li></ul><pre>df_cached = df.filter(df.Age &gt; 30).cache()<br>df_cached.count()<br>df_cached.show()</pre><h3>📦 What About persist()?</h3><p>persist() is more flexible than cache().</p><p>By default:</p><pre>df.persist()</pre><p>is the <strong>same as</strong> .cache() → it stores data in <strong>memory only</strong>.</p><p>But you can also choose other <strong>storage levels</strong>:</p><h3>🧊 Examples:</h3><pre>from pyspark import StorageLevel</pre><pre>df.persist(StorageLevel.MEMORY_AND_DISK)<br>df.persist(StorageLevel.DISK_ONLY)</pre><h3>🧪 StorageLevel Options</h3><p>Storage Level Description MEMORY_ONLY (default cache) Fastest; errors if data doesn&#39;t fit in RAM MEMORY_AND_DISK Falls back to disk if RAM is full DISK_ONLY No RAM usage; slower but stable MEMORY_ONLY_SER Serialized form; reduces memory footprint</p><h3>💡 When to Use Which?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*2xmlBLPD4JMIITFF.png" /></figure><h3>⚠️ Important Notes</h3><ul><li>Always <strong>unpersist</strong> manually if you’re done:</li></ul><pre>df.unpersist()</pre><ul><li>Don’t cache or persist everything — it consumes memory</li><li>Use <strong>Spark UI → Storage tab</strong> to monitor memory usage</li></ul><h3>🧠 Analogy:</h3><p><strong>Think of </strong><strong>cache() as pinning something to your clipboard</strong> — fast, in-RAM, disposable.</p><p><strong>persist() is like choosing how and where to store it — clipboard, local drive, or cloud.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04be47fc0dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partitioning in Spark — Why It Matters & How to Use It]]></title>
            <link>https://medium.com/@dlamine9/partitioning-in-spark-why-it-matters-how-to-use-it-b14f35335361?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14f35335361</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark-tutorial]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 20:31:10 GMT</pubDate>
            <atom:updated>2025-04-04T20:31:10.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>Partitioning in Spark — Why It Matters &amp; How to Use It</h3><p>Welcome to <strong>Day 7</strong> of my <strong>30-Day Databricks Crash Course</strong>!<br> Today, we’re diving into a crucial performance topic: <strong>partitioning in Spark</strong>.</p><p>If your Spark jobs are slow or unbalanced, there’s a good chance your <strong>partitions need tuning</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2w73aOz3fCzHjPYb-cTfwA.jpeg" /></figure><p><strong>Partitioning.</strong></p><p>If you’ve ever asked:</p><p>“Why is my job slow?”</p><p>“Why is there data skew?”</p><p>“Why does my cluster run out of memory?”</p><p>…then partitioning is the answer.</p><h3>🧱 What Is Partitioning in Spark?</h3><p>Partitioning refers to how <strong>data is split across the cluster</strong> — into slices that Spark can process <strong>in parallel</strong>.</p><p>Each <strong>partition = one task</strong>.<br>More partitions → better parallelism (to a point).<br>Too few → underutilized CPUs.<br>Too many → overhead &amp; memory bloat</p><h3>🔍 Why Partitioning Matters</h3><ul><li>✅ Enables better <strong>parallelism</strong></li><li>✅ Controls <strong>shuffle sizes</strong></li><li>✅ Prevents <strong>data skew</strong> (when one node does all the work)</li><li>✅ Affects <strong>task distribution and performance</strong></li></ul><h3>⚙️ Default Partitioning Behavior</h3><p>By default:</p><pre>df.rdd.getNumPartitions()</pre><p>This will often return <strong>200</strong>, the Spark default.<br>But this isn’t always optimal — it depends on <strong>data size</strong> and <strong>cluster resources</strong>.</p><h3>🧪 Repartitioning in PySpark</h3><h4>🔁 repartition() – Full shuffle, evenly distributed</h4><pre>df_re = df.repartition(100)</pre><h4>➖ coalesce() – Reduces partitions, without shuffle</h4><pre>df_co = df.coalesce(10)</pre><p>💡 Use coalesce() after filtering or narrowing results.<br>Use repartition() before wide operations like groupBy.</p><h3>📊 Real Example</h3><pre>df = spark.read.csv(&quot;/FileStore/tables/huge_file.csv&quot;, header=True, <br>inferSchema=True)<br><br>print(df.rdd.getNumPartitions())  # Check before<br><br>df = df.repartition(50)<br>print(df.rdd.getNumPartitions())  # After repartitioning</pre><h3>🧠 When to Tune Partitions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*con1nUaxYWnXD_nk.png" /></figure><h3>⚠️ Partitioning Pitfalls</h3><ul><li>❌ Avoid repartition(1) unless you really need a single output file</li><li>❌ Don’t over-partition small datasets</li><li>✅ Always monitor task execution in the <strong>Spark UI</strong></li></ul><p>🔗 Related Posts</p><p>➡️ <a href="#">Day 6: Spark Jobs, Stages &amp; Tasks Explained</a><br>➡️ <a href="#">Day 8: Cache vs Persist in Spark — Storage Levels Demystified</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14f35335361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚙️ Day 6: Spark Jobs, Stages & Tasks — What Actually Happens When You Run Code]]></title>
            <link>https://medium.com/@dlamine9/%EF%B8%8F-day-6-spark-jobs-stages-tasks-what-actually-happens-when-you-run-code-9383184b5c58?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9383184b5c58</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 18:05:57 GMT</pubDate>
            <atom:updated>2025-04-04T20:04:13.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spark Jobs, Stages &amp; Tasks — What <em>Actually</em> Happens When You Run Code</h3><p>Welcome to <strong>Day 6</strong> of the 30-Day Databricks Crash Course!<br> You’ve been writing code, running transformations, and triggering actions — but have you ever wondered…</p><p><strong>What actually happens under the hood when Spark runs your job?</strong></p><p>Let’s break it down simply:<br> <strong>Spark Jobs → Stages → Tasks.</strong></p><h3>🧠 What Is a Spark Job?</h3><p>A <strong>Spark job</strong> is triggered when you call an <strong>action</strong> like .show(), .count(), or .collect().</p><p>Think of it like pressing “Run” on your full data pipeline.<br> That job is <strong>divided into smaller execution units</strong> for efficiency.</p><h3>⚙️ What Are Stages?</h3><p>Spark breaks the job into <strong>stages</strong> — logical groups of operations based on data shuffles.</p><h3>🔹 Types of stages:</h3><ul><li><strong>Narrow Stage</strong>: Data can stay on the same partition (e.g., filter, select)</li><li><strong>Wide Stage</strong>: Requires <strong>shuffling</strong> data across nodes (e.g., groupBy, join)</li></ul><p>Each stage = a boundary where <strong>data movement happens</strong>.<br> More stages = more time and network I/O.</p><h3>🔄 What Are Tasks?</h3><p>Each stage is further broken into <strong>tasks</strong>, which run in parallel.</p><p>✅ One <strong>task per partition</strong>, per core.<br> If you have 100 partitions and 10 cores, Spark will try to run 10 tasks in parallel until all 100 are done.</p><h3>🧩 Think of it like:</h3><pre>Job<br> └── Stage 1 (Narrow)<br>     ├── Task 1<br>     ├── Task 2<br>     └── Task N<br> └── Stage 2 (Wide)<br>     ├── Task 1<br>     ├── Task 2<br>     └── Task N</pre><h3>🔍 Example in Action</h3><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&quot;Day6Job&quot;).getOrCreate()</pre><pre>df = spark.read.csv(&quot;/FileStore/tables/employees.csv&quot;, header=True, inferSchema=True)<br><br># Transformation<br>df_grouped = df.groupBy(&quot;department&quot;).avg(&quot;salary&quot;)<br><br># Action<br>df_grouped.show()</pre><p>Here’s what happens:</p><ul><li>.groupBy() triggers a <strong>wide transformation</strong>, so Spark sets up a shuffle.</li><li>.show() triggers a <strong>job</strong> with multiple stages.</li><li>Each stage gets split into <strong>parallel tasks</strong>.</li></ul><h3>🔧 Where to See This in Databricks?</h3><ol><li>After running a job, click on <strong>“View Spark UI”</strong></li><li>Navigate to <strong>Jobs → Stages → Tasks</strong></li><li>You’ll see DAGs, time taken, task attempts, etc.</li></ol><p>This is gold for debugging performance.</p><h3>📸 Visual Time</h3><p>Let’s create a visual that maps <strong>Jobs → Stages → Tasks</strong> with labels and an easy-to-digest layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eba71F3oktJ95AGyQBZLRA.jpeg" /></figure><p>✅ Here’s your <strong>Day 6 visual</strong> — a clear infographic showing the <strong>Spark execution hierarchy: Jobs → Stages → Tasks</strong>, with brief explanations and a clean design. Great for LinkedIn, Medium, or slides!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9383184b5c58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Day 4: Mastering DataFrames in Databricks (PySpark Basics)]]></title>
            <link>https://medium.com/@dlamine9/day-4-mastering-dataframes-in-databricks-pyspark-basics-775ed2e97068?source=rss-b5c7b133cbe3------2</link>
            <guid isPermaLink="false">https://medium.com/p/775ed2e97068</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data-analysis]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[El Amin]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 15:19:02 GMT</pubDate>
            <atom:updated>2025-04-04T20:03:20.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering DataFrames in Databricks (PySpark Basics)</h3><p>Welcome to <strong>Day 4</strong> of the <strong>30-Day Databricks Series</strong>!<br> Today, we’re diving into the <strong>core skill</strong> every data engineer should master: <strong>DataFrames in PySpark</strong>.</p><p>If you’re confident with DataFrames, you’re already 80% of the way to building real data pipelines. Let’s go hands-on 👇</p><h3>🔍 What is a DataFrame?</h3><p>A <strong>DataFrame</strong> is a distributed table-like structure with rows and columns — think Excel meets SQL meets Big Data.</p><p>It’s optimized for parallel computation and supports:</p><ul><li>Schema enforcement ✅</li><li>Column-based operations ✅</li><li>SQL queries ✅</li></ul><h3>📥 Creating a DataFrame</h3><p>Here’s how to define one manually:</p><pre>data = [(&quot;Alice&quot;, 28), (&quot;Bob&quot;, 35), (&quot;Charlie&quot;, 40)]<br>df = spark.createDataFrame(data, [&quot;Name&quot;, &quot;Age&quot;])<br>df.show()</pre><h3>🔎 Inspecting the Data</h3><p>Quick checks help you understand your data:</p><pre>df.printSchema()<br>df.describe().show()<br>df.columns</pre><h3>✂️ Filtering Rows</h3><p>You can filter rows using filter() or where():</p><pre>df.filter(df.Age &gt; 30).show()<br># or<br>df.where(&quot;Age &lt; 35&quot;).show()</pre><h3>➕ Adding New Columns</h3><p>Use withColumn() to transform or enrich data:</p><pre>from pyspark.sql.functions import col</pre><pre>df = df.withColumn(&quot;AgePlusFive&quot;, col(&quot;Age&quot;) + 5)<br>df.show()</pre><h3>📐 Selecting Columns</h3><p>Only want a few columns?</p><pre>df.select(&quot;Name&quot;).show()<br>df.select(col(&quot;Name&quot;), (col(&quot;Age&quot;) * 2).alias(&quot;DoubleAge&quot;)).show()</pre><h3>🔁 Chaining Transformations</h3><p>Chaining lets you build efficient one-liners</p><pre>df.filter(df.Age &gt; 30)\<br>  .withColumn(&quot;AgeSquared&quot;, col(&quot;Age&quot;)**2)\<br>  .select(&quot;Name&quot;, &quot;AgeSquared&quot;)\<br>  .show()</pre><h3>🗂️ Optional: Load External Data</h3><p>Here’s how to load from a CSV or Parquet file:</p><pre># CSV<br>df_csv = spark.read.csv(&quot;/FileStore/tables/mydata.csv&quot;, header=True, inferSchema=True)</pre><pre># Parquet<br>df_parquet = spark.read.parquet(&quot;/FileStore/tables/mystorage</pre><h3>📸 Visual Reference</h3><p>Add this image to your post for visual learners:<br> <strong>“PySpark DataFrame Operations Cheat Sheet”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmbW1K2-EwjXSWvjpVSpOA.jpeg" /></figure><h3>✅ Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*PaQX9-WUbKcHB5B4Q0oW2g.png" /></figure><h3>🧠 What’s Next?</h3><p>Coming up tomorrow:</p><p>📅 Day 5 — <em>Transformations &amp; Actions in PySpark: Understanding the Lazy Evaluation Model</em></p><p>Stay tuned — and try these code blocks in your notebook today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775ed2e97068" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>