<?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 Rama Krishna Nutalapati on Medium]]></title>
        <description><![CDATA[Stories by Rama Krishna Nutalapati on Medium]]></description>
        <link>https://medium.com/@rknutalapati?source=rss-577ca3361e21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zLROmFvxFkYu0cYOcCyH0w.png</url>
            <title>Stories by Rama Krishna Nutalapati on Medium</title>
            <link>https://medium.com/@rknutalapati?source=rss-577ca3361e21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:24:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rknutalapati/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[I Gave Databricks Genie the Wrong Data Types — Here’s What Happened]]></title>
            <link>https://rknutalapati.medium.com/i-gave-databricks-genie-the-wrong-data-types-heres-what-happened-dd7b55d3858a?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd7b55d3858a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[genie]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 03:06:57 GMT</pubDate>
            <atom:updated>2026-09-02T03:06:57.542Z</atom:updated>
            <content:encoded><![CDATA[<p>We all know that choosing the correct data type is important.</p><p>Customer IDs should have the right type. Amounts should be numeric. Dates should be dates.</p><p>But I wanted to test this from a different angle.</p><p>What happens when Databricks Genie works with tables that have the wrong data types?</p><ul><li>Will it still answer the question?</li><li>What SQL will it generate?</li><li>And can the table design affect the work happening behind the answer?</li></ul><p>So I ran a small experiment.</p><p>The Experiment</p><p>I created two versions of customer and order data.</p><p>Each version had:</p><ul><li><strong>50,000 customers</strong></li><li><strong>500,000 orders</strong></li></ul><p>In the first version, I used the correct data types.</p><pre>-- customers<br>customer_id INT<br><br>-- orders<br>customer_id INT<br>total_amount DECIMAL(10,2)</pre><p>In the second version, I intentionally created two data type problems.</p><pre>-- customers<br>customer_id STRING<br><br>-- orders<br>customer_id INT<br>total_amount STRING</pre><p>So I had two things to test.</p><p>The customer ID used for the join had a type mismatch.</p><pre>STRING &lt;-&gt; INT</pre><p>And <em>total_amount</em>, which should be numeric, was stored as a <em>STRING</em>.</p><p>I then used these tables with Genie and asked the same business questions.</p><h4>Test 1: Show Top 5 Orders by Total Amount</h4><p>Both versions returned the answer. But when I looked at the SQL generated by Genie, I saw a difference.</p><p>For the table with the wrong data type, Genie generated —</p><pre>ORDER BY<br>  CAST(total_amount AS DECIMAL(10,2)) DESC</pre><p>Because <em>total_amount </em>was stored as a <em>STRING</em>, Genie generated a numeric conversion before sorting it.</p><p>With the correct data type, Genie generated</p><pre>-- CAST was not needed.<br>ORDER BY<br>  total_amount DESC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VusO_NzjcWAx3r5GffZxiQ.jpeg" /></figure><p>This was my first observation:</p><blockquote>Genie was able to work around the bad data type, but the workaround became part of the generated SQL.</blockquote><h4>Test 2: Join Customers and Orders</h4><p>Next, I asked</p><blockquote>Show customer names with their total spending</blockquote><p>This test was more interesting because Genie had to join the two tables and calculate the total spending.</p><p>With the correct data types, the join was simple.</p><pre>ON c.customer_id = o.customer_id<br><br>--And the amount could be used directly:<br>SUM(o.total_amount)</pre><p>With the wrong data types, Genie had to deal with the mismatch.</p><p>In one test, it generated:</p><pre>ON CAST(c.customer_id AS INT) = o.customer_id<br><br>-- It also converted the amount before calculating the total:<br>SUM(CAST(o.total_amount AS DECIMAL(16,2)))</pre><p>The query still worked, but the generated SQL had additional conversion logic because of the column types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhQN_Z8vjnOZKbzxT5U9VQ.jpeg" /></figure><h4>Then I Saw Something More Interesting</h4><p>During my testing, I also added and deleted some data from the tables. When I tested again with the wrong data types, Genie generated the join differently.</p><p>It generated</p><pre>c.customer_id = CAST(o.customer_id AS STRING)<br></pre><p>After running <strong>ANALYZE TABLE</strong> to refresh the statistics and asking the same question again, Genie generated:</p><pre>CAST(c.customer_id AS INT) = o.customer_id</pre><p>So in my tests, the available table statistics appeared to influence how Genie generated the SQL for the same type mismatch.</p><ul><li>STRING → INT</li><li>INT → STRING</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpY-4qWnaP4S6zLvlMAONw.jpeg" /></figure><h4>What About Performance?</h4><p>Next, I wanted to see whether the difference was visible during execution.</p><p>My first few tests gave confusing results because queries were running close together on a small warehouse.</p><p>So I repeated the tests separately.</p><p>In one isolated comparison, I observed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*4qIFJXPfeIsTs8CLK8N_Gg.png" /></figure><p>The correct-type query was faster in this particular test.</p><p>But I want to be careful with this result.</p><p><strong>This does not mean wrong data types will always make a query 5 or 6 times slower.</strong></p><p>Query performance can also be affected by caching, warehouse state, file layout, query plans and other factors.</p><p>I saw this in my own testing.</p><p>In another wrong-type run, the query completed much faster and the Query Profile showed that about <strong>98% of the bytes were read from cache</strong>.</p><p>That is why I don’t want to present these results as a benchmark.</p><p>My takeaway from this part is simpler:</p><blockquote>Wrong data types can introduce extra conversion work. How much that affects performance depends on the query and environment.</blockquote><h4>What About Cost?</h4><p>There is also a possible cost impact.</p><p>If a query runs once, a little extra work may not matter much.</p><p>But what if the same query pattern runs <strong>1,000 times every day</strong>?</p><p>Using the execution times from my isolated test, I made a simple runtime-based cost illustration.</p><p>Under the assumptions I used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*I95tClRJ_LTageylCxXaJg.png" /></figure><p>In this simple calculation, that gives roughly <strong>$171 difference per year for one repeated query pattern</strong>.</p><p>But I want to be clear</p><blockquote><strong><em>These are not actual Databricks billing numbers.</em></strong></blockquote><p>Real SQL compute cost depends on the warehouse configuration, runtime, concurrency, workload and billing model.</p><p>The exact dollar amount is not the main point.</p><p>The same tables may be used by Genie questions, dashboards, reports, APIs and other workloads.</p><p>So a small schema problem can be repeated many times.</p><p>Here I am talking about the compute used to execute the generated SQL, not the price of the Genie feature itself.</p><h4>My Takeaway</h4><p>Genie did a good job handling the bad schema in my tests.</p><p>It was able to handle the type mismatch and still return the expected answer.</p><p>But I don’t think we should depend on Genie to fix data modeling problems at query time.</p><p>A simple business question could result in additional type conversions underneath.</p><blockquote>AI can generate the SQL, but good data modeling still matters.</blockquote><p>Correct data types can give us simpler SQL, fewer conversions and more predictable query behavior.</p><p>Genie can work around some schema problems.</p><p><strong>But that workaround is not always free.</strong></p><p>GitHub: [ <a href="https://github.com/RKNUTALAPATI/build-break-learn/blob/main/medium/Genie_DataTypes_Impact_Testing.py">Databricks Genie — Data Type Experiment</a> ]</p><p><em>This was a small experiment using 50,000 customers and 500,000 orders. The performance and cost numbers are specific to my test setup and assumptions. They should not be treated as general Databricks benchmarks.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd7b55d3858a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a 1 Million Vector Search in Databricks — Here’s Why Vector Databases Feel So Fast]]></title>
            <link>https://rknutalapati.medium.com/i-built-a-1-million-vector-search-in-databricks-heres-why-vector-databases-feel-so-fast-94e9ef07ca37?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e9ef07ca37</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 18:36:31 GMT</pubDate>
            <atom:updated>2026-07-04T18:53:33.628Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A beginner-friendly guide to embeddings, cosine similarity, and a real Databricks experiment showing why brute-force search doesn’t scale.</blockquote><p>Have you ever wondered how ChatGPT, Gemini, or Claude can search through millions of documents and answer your question in just a few seconds?</p><p><strong>One of the key technologies behind this is the vector database.</strong></p><p>But before we understand how vector databases work, we first need to understand two fundamental concepts: <strong>embeddings</strong> and <strong>cosine similarity</strong>.</p><p>In this article, we’ll explore:</p><ul><li>What embeddings are</li><li>What cosine similarity means</li><li>How vector search works</li><li>Why brute-force search does not scale</li><li>Why vector databases use special indexing techniques to make search fast</li></ul><p>The goal of this article is not to teach a specific tool or library. Instead, we’ll build a strong understanding of the core concepts that power modern AI applications.</p><h4>What is an Embedding?</h4><p>Computers don’t understand the meaning of text the way humans do.. For example, if we have two sentences.</p><ul><li>I will sleep early today.</li><li>Production deployment starts at 10 PM.</li></ul><p>Every software engineer immediately understands what is happening here 😊.</p><p>Even though the two sentences use completely different words, humans can easily understand that they are related. The second sentence explains why the first plan may not work!</p><p>However, computers do not naturally understand such relationships. For a computer, these are just pieces of text.</p><p>To help computers understand meaning, Machine Learning models convert text into a list of numbers called an <strong>embedding</strong>.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*UDMk1mLYCVnXD5YHAHje4A.png" /></figure><p>Since both sentences are semantically related, their embeddings will be placed close to each other in a high-dimensional space.</p><p>An embedding can be thought of as a location on a map of meaning.</p><p>The important idea is:</p><blockquote><em>Similar meanings produce similar vectors, even if the actual words are different.</em></blockquote><p>Modern embedding models usually generate vectors with dimensions like:</p><ul><li>384</li><li>768</li><li>1536</li><li>3072</li></ul><h4>What is Cosine Similarity?</h4><p>Now that we have embeddings, the next question is — <em>How do we compare two embeddings?</em></p><p>This is where cosine similarity comes in.Cosine similarity measures how closely two vectors point in the same direction.Instead of looking at the length of the vectors, it compares their direction.</p><p>Simple analogy. Imagine two people walking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIMdRiA70AXCU5W1yBiJzQ.png" /></figure><blockquote>In simple words, the more two vectors point in the same direction, the more similar they are. This is why documents with similar meaning receive higher cosine similarity scores, even if they don’t use the exact same words.</blockquote><h3>How Does Vector Search Work?</h3><p>Suppose a user searches for:</p><pre>best puppy food</pre><p>The search process looks like this:</p><p><strong>Step 1</strong></p><p>Convert the search text into an embedding.</p><pre>[0.21, -0.67, 0.54, ...]</pre><p><strong>Step 2</strong></p><p>Compare this query vector against all stored document vectors.</p><p>Example:</p><p>The query “best puppy food” produced the following similarity scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*j03jPHVuAFi1TrU7MrpDUw.png" /></figure><p>As expected, documents related to pets received much higher scores than an unrelated topic like car maintenance.</p><p><strong>Step 3</strong></p><p>Return the top matching documents.</p><p>This is called semantic search because the system searches based on meaning rather than exact keywords.</p><h4>Can We Compare Against Every Vector?</h4><p>Yes.This method is called <em>brute-force search.</em>The algorithm is simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*nyosgerBRjIWGJtSCtcuuQ.png" /></figure><p>This approach works well for small datasets.</p><p>But what happens if we have:</p><ul><li>1 million vectors?</li><li>100 million vectors?</li><li>1 billion vectors?</li></ul><p>The search becomes expensive.</p><h3>Practical Experiment in Databricks</h3><p>To understand this better, I generated 1 million vectors in Databricks and performed brute-force cosine similarity search.</p><p>Cluster Configuration:</p><ul><li>DBR 15.x</li><li>2 workers</li><li>16 GB memory per worker</li></ul><p>Dataset:</p><ul><li>1,000,000 vectors</li><li>64 dimensions</li></ul><h4>Experiment Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*eWHchM2s0WEQKObl0sfaEQ.png" /></figure><p>Even though Spark distributed the work across multiple executors, it still had to scan all one million vectors.</p><p>The important observation is:</p><blockquote><em>Spark distributed the computation, but the algorithm still remained O(N).</em></blockquote><p>In other words, every query still required scanning the entire dataset.This is the main reason vector databases use special indexing algorithms.</p><h3>Source Code</h3><p>To keep this article focused on the concepts, I haven’t included the complete implementation here.</p><p>The full project includes:</p><p>• Databricks Notebook<br> • Standalone Python implementation<br> • Benchmark results<br> • Spark job and stage metrics<br> • Project documentation</p><p>You can find everything on GitHub:<br> <br>👉 <a href="https://github.com/RKNUTALAPATI/build-break-learn/tree/main/ai/vector-databases/embeddings">View the complete project on GitHub</a></p><h3>Why Vector Databases Feel Fast</h3><p>Real-time applications cannot afford to scan millions of vectors for every query.</p><p>Imagine ChatGPT,Gemini, Claude taking 10 seconds for every question.That would not be acceptable.</p><p>Instead of checking every vector, vector databases use Approximate Nearest Neighbor (ANN) algorithms.ANN algorithms try to answer:</p><blockquote><em>“Can we find the closest vectors without scanning everything?”</em></blockquote><p>The answer is yes.</p><h3>Important Trade-Off</h3><p>ANN algorithms do not always return the exact nearest neighbor. Instead, they trade a small amount of accuracy for a huge improvement in speed.</p><p>Example:</p><pre>Exact Search:<br>100% accurate<br>10 seconds<br><br>ANN Search:<br>99% accurate<br>50 milliseconds</pre><p>For most AI applications, this trade-off is acceptable.</p><h3>Final Thoughts</h3><p>Vector databases are not magic. They are built on a few simple but powerful ideas working together.</p><p>At their core:</p><ul><li><strong>Embeddings</strong> convert meaning into numbers.</li><li><strong>Cosine similarity</strong> measures how semantically similar two vectors are.</li><li><strong>Brute-force search</strong> compares a query against every stored vector.</li><li><strong>ANN algorithms</strong> such as <strong>HNSW</strong> make large-scale vector search fast and practical.</li></ul><p>The biggest lesson I learned from this experiment wasn’t how to generate embeddings — it was realizing that <strong>searching millions of embeddings efficiently is the real challenge</strong>.</p><p>And that’s exactly where vector databases shine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e9ef07ca37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks Apps Don’t Auto-Stop — and It’s Quietly Costing You Money (Here’s How I Fixed It)]]></title>
            <link>https://rknutalapati.medium.com/databricks-apps-dont-auto-stop-and-it-s-quietly-costing-you-money-here-s-how-i-fixed-it-d242ffdbaa67?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/d242ffdbaa67</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 01:32:28 GMT</pubDate>
            <atom:updated>2026-04-10T01:32:28.742Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem Nobody Notices</h3><p>Databricks Apps are great for deploying dashboards, APIs, and internal tools.</p><p>But there’s a catch:</p><p><strong>They never stop.</strong></p><p>Unlike clusters or SQL warehouses, there is:</p><ul><li>No auto-termination</li><li>No idle timeout</li><li>No built-in lifecycle control</li></ul><p>So what happens in real environments?</p><ul><li>Dev/test apps run all night</li><li>Temporary apps are forgotten</li><li>Internal tools sit idle for days</li></ul><p>And quietly — <strong>DBUs keep burning</strong>.</p><h3>Why This Matters (More Than You Think)</h3><p>This isn’t just a minor inefficiency.</p><p>In most teams:</p><ul><li>Nobody owns app lifecycle</li><li>There’s no visibility into idle usage</li><li>Costs show up later — not in real time</li></ul><p>Even a handful of idle apps can translate into <strong>significant monthly waste</strong>.</p><p>And the worst part?</p><blockquote><em>There is currently no native way to fix this in Databricks Apps.</em></blockquote><h3>What I Built Instead</h3><p>To solve this, I built a small automation using the Databricks SDK that:</p><ul><li>Scans all running apps</li><li>Detects inactivity based on last update</li><li>Flags apps idle beyond a threshold</li><li>Stops them safely</li><li>Logs everything for audit</li></ul><p>No external services. No complex setup. Just a simple, repeatable pattern.</p><h3>Design Principles</h3><p>Before jumping into code, a few important decisions made this production-safe:</p><h3>1. Only Touch Running Apps</h3><p>We explicitly filter:</p><ul><li>ACTIVE apps only</li><li>Ignore stopped or unknown states</li></ul><p>This avoids unnecessary API calls and risk.</p><h3>2. Reliable Idle Detection</h3><p>We determine last activity using:</p><ul><li>active_deployment.update_time (primary signal)</li><li>fallback → app.update_time</li></ul><p>This ensures consistency even across different app states.</p><h3>3. Safe Rollout with Dry Run</h3><p>Always start with:</p><pre>DRY_RUN = True</pre><p>This lets you:</p><ul><li>Validate behavior</li><li>Review impacted apps</li><li>Avoid accidental shutdowns</li></ul><h3>4. Audit Everything</h3><p>Instead of relying on logs, we generate a structured dataset with:</p><ul><li>App name</li><li>Last activity</li><li>Idle duration</li><li>Action taken</li></ul><p>This becomes your:</p><ul><li>Cost visibility layer</li><li>Governance record</li><li>Debugging tool</li></ul><p>The Script</p><pre>from databricks.sdk import WorkspaceClient <br>from datetime import datetime, timezone, timedelta<br>from pyspark.sql.types import StructType, StructField, StringType, DoubleType, TimestampType<br><br>IDLE_THRESHOLD_HOURS = 1<br>DRY_RUN = False<br><br>w = WorkspaceClient()<br><br>get_apps = list(w.apps.list())<br>print(f&quot;Total apps found: {len(get_apps)}&quot;)<br>print(f&quot;Idle threshold: {IDLE_THRESHOLD_HOURS} hours&quot;)<br>print(f&quot;Dry run: {DRY_RUN}\n&quot;)<br><br>now = datetime.now(timezone.utc)<br>idle_apps = []<br>app_records = []<br><br>for app in get_apps:<br>    compute_state = str(app.compute_status.state) if app.compute_status else &quot;UNKNOWN&quot;<br><br>    if compute_state not in (&quot;ACTIVE&quot;, &quot;ComputeState.ACTIVE&quot;):<br>        continue<br><br>    last_activity = None<br>    if app.active_deployment and app.active_deployment.update_time:<br>        last_activity = app.active_deployment.update_time<br>    elif app.update_time:<br>        last_activity = app.update_time<br><br>    if last_activity:<br>        if isinstance(last_activity, str):<br>            last_activity = datetime.fromisoformat(last_activity.replace(&quot;Z&quot;, &quot;+00:00&quot;))<br>        if last_activity.tzinfo is None:<br>            last_activity = last_activity.replace(tzinfo=timezone.utc)<br>        idle_duration = now - last_activity<br>        idle_hours = round(idle_duration.total_seconds() / 3600, 1)<br>        is_idle = idle_hours &gt; IDLE_THRESHOLD_HOURS<br>    else:<br>        idle_hours = None<br>        is_idle = False<br><br>    action = &quot;WILL STOP&quot; if is_idle and not DRY_RUN else &quot;WOULD STOP&quot; if is_idle else &quot;ACTIVE&quot;<br><br>    app_records.append({<br>        &quot;app_name&quot;: app.name,<br>        &quot;status&quot;: &quot;ACTIVE&quot;,<br>        &quot;last_activity&quot;: last_activity,<br>        &quot;idle_hours&quot;: float(idle_hours) if idle_hours is not None else None,<br>        &quot;action&quot;: action,<br>        &quot;evaluated_at&quot;: now<br>    })<br><br>    if is_idle:<br>        idle_apps.append((app, idle_hours))<br><br>schema = StructType([<br>    StructField(&quot;app_name&quot;, StringType(), False),<br>    StructField(&quot;status&quot;, StringType(), False),<br>    StructField(&quot;last_activity&quot;, TimestampType(), True),<br>    StructField(&quot;idle_hours&quot;, DoubleType(), True),<br>    StructField(&quot;action&quot;, StringType(), False),<br>    StructField(&quot;evaluated_at&quot;, TimestampType(), False)<br>])<br><br>df_app_audit = spark.createDataFrame(app_records, schema=schema)<br>print(f&quot;Running apps: {df_app_audit.count()}&quot;)<br>print(f&quot;Idle apps (&gt;{IDLE_THRESHOLD_HOURS}h): {len(idle_apps)}\n&quot;)<br># display(df_app_audit)<br># Write to &lt;Audit Table&gt;<br>if idle_apps:<br>    print(f&quot;\n{&#39;--- DRY RUN ---&#39; if DRY_RUN else &#39;--- STOPPING IDLE APPS ---&#39;}&quot;)<br>    for app, hrs in idle_apps:<br>        if DRY_RUN:<br>            print(f&quot;  [DRY RUN] Would stop: {app.name} (idle {hrs}h)&quot;)<br>        else:<br>            try:<br>                w.apps.stop(app.name)<br>                print(f&quot;  Stopped: {app.name} (was idle {hrs}h)&quot;)<br>            except Exception as e:<br>                print(f&quot;  Failed to stop {app.name}: {e}&quot;)<br>else:<br>    print(&quot;\nNo idle apps to stop. All running apps are within the activity threshold.&quot;)</pre><h3>How to Run This in Production</h3><p>Keep it simple:</p><ul><li>Schedule via Databricks Workflows</li><li>Or trigger from ADF / Airflow if already in place</li></ul><p>No need to over-engineer this.</p><h3>What This Unlocks</h3><p>This small script gives you:</p><ul><li>Immediate cost control</li><li>Visibility into idle usage</li><li>A foundation for FinOps practices</li></ul><p>And most importantly:</p><blockquote><em>It stops paying for compute nobody is using</em></blockquote><h3>Production Enhancements (Optional but Powerful)</h3><p>If you want to take this further:</p><ul><li>Add allowlist for critical apps</li><li>Persist audit logs to Delta tables</li><li>Add alerting (Slack / Email)</li><li>Introduce tag-based shutdown (dev/test only)</li><li>Build a simple cost dashboard</li></ul><p>Until auto-stop exists for Apps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d242ffdbaa67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“It Works Locally” — Why Your Python Wheel Breaks on Databricks (ModuleNotFoundError & Executor…]]></title>
            <link>https://rknutalapati.medium.com/it-works-locally-why-your-python-wheel-breaks-on-databricks-modulenotfounderror-executor-fda4702b8ede?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/fda4702b8ede</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 21:01:33 GMT</pubDate>
            <atom:updated>2026-02-13T21:04:03.533Z</atom:updated>
            <content:encoded><![CDATA[<h3>“It Works Locally” — Why Your Python Wheel Breaks on Databricks (ModuleNotFoundError &amp; Executor Import Issues Explained)</h3><blockquote>A practical debugging guide for distributed Python environments on Databricks — driver vs executors, wheel packaging, and ABI issues explained.</blockquote><p>You built the package.<br>You validated it locally.<br>Unit tests passed.<br>The wheel installs cleanly. <br>It imports in the notebook.</p><p>From a packaging standpoint, everything looks correct.</p><p>Then the Databricks job cluster starts… and fails.</p><pre>ModuleNotFoundError: No module named ...<br>A module compiled with NumPy 1.x cannot run in NumPy 2.x<br>PyArrow not found<br>Spark worker failed to deserialize</pre><p>Nothing in your code changed. But everything behaves differently.</p><p>If you’ve shipped Python wheels into distributed Spark environments, you already know. Local success means very little.</p><p>This guide walks through the real reasons wheels fail on Databricks — and how to systematically troubleshoot them.</p><p>No guesswork. No random <em>pip installs</em>.<br>Just a structured debugging approach that works in production environments.</p><p><strong>The Notebook Is Not Production</strong></p><p>If it runs in a notebook cell but fails during a job or distributed execution,<br>your workers cannot see your package.</p><p>Notebook installs live only in the interactive session.<br>Distributed workloads run in separate environments.</p><p>Different process. Different runtime. Different visibility.</p><p><strong>Step 1: Verify the Wheel Is Actually Installed</strong></p><p>Don’t trust the UI. Always verify from the notebook.</p><p>Check installed packages</p><pre>%pip list | grep your-package-name </pre><p>Verify import location</p><pre>import importlib.util<br>print(importlib.util.find_spec(&quot;your_package&quot;))</pre><p>If this returns None, your package is not installed in that environment.<br>If it shows a path under something like:</p><pre>…/cluster_libraries/python/lib/python3.11/site-packages</pre><p>Then it’s installed — at least on the driver.</p><p><strong>Step 2: Driver Works, Executors Fail</strong></p><p>Some code runs perfectly in a notebook cell but crashes when executed inside distributed transformations.</p><p>This typically happens when your logic runs inside</p><ul><li>A distributed DataFrame transformation</li><li>A vectorized function</li><li>A Pandas-based Spark operation</li><li>A user-defined function (UDF)</li><li>Any operation executed on worker nodes</li></ul><p>For example:</p><pre>mapInPandas, applyInPandas, Pandas UDFs, rdd.map(), foreachPartition</pre><p>In these cases, your function is no longer running in the notebook process.<br>It is serialized and sent to worker nodes.</p><p>That’s where the failure happens.</p><pre>ModuleNotFoundError<br>Spark worker failed to deserialize<br>No module named ...</pre><p>What actually happens under the hood when you call a distributed transformation</p><ul><li>Spark serializes your function.</li><li>It ships that function to executor nodes.</li><li>Executors attempt to import your modules.</li><li>If the package is not available there → it fails.</li></ul><p>Fix checklist</p><ul><li>Attach the wheel at the cluster level (not notebook-scoped only)</li><li>Ensure it is installed before Spark starts</li><li>Restart cluster after installation</li><li>Verify import from executors</li></ul><pre># Check Library Path<br>spark.sparkContext<br>.parallelize([1])<br>.map(lambda x: __import__(&quot;your_package&quot;))<br>.collect()<br></pre><p>If this fails, executors cannot see the wheel.</p><p><strong>Step 3: Your Wheel Structure Might Be Wrong</strong></p><p>This is extremely common. If your wheel only includes</p><ul><li>your_package/__init__.py</li><li>your_package/__main__.py</li></ul><p>But your code imports<br>from your_package.some_module import SomeClass</p><p>And that file wasn’t included in the build — it will fail.</p><p><strong>Verify Wheel Contents</strong></p><pre>pip show -f your-package-name</pre><p>Or inside databricks</p><pre>import importlib_metadata as md<br><br>dist = md.distribution(&quot;your-package-name&quot;)<br>print(dist.version)<br><br>files = [str(f) for f in dist.files]<br><br>for f in files:<br>    if &quot;&lt;name&gt;&quot; in f.lower() or &quot;&lt;name&gt;&quot; in f.lower() or &quot;&lt;name&gt;&quot; in f.lower():<br>        print(f)</pre><p>Confirm all expected .py files are packaged.</p><p>If not:</p><ul><li>Ensure your packaging configuration includes the full module</li><li>Ensure your module folder actually contains the files before build</li><li>Rebuild the wheel cleanly</li></ul><p><strong>Step 4: NumPy / PyArrow Version Explosion</strong></p><p>You may see errors like:</p><pre>A module compiled using NumPy 1.x cannot be run in NumPy 2.x<br>AttributeError: _ARRAY_API not found<br>PyArrow &gt;= 4.0.0 must be installed</pre><p>This is not your application logic. This is ABI(<em>Application Binary Interface</em>) incompatibility between compiled libraries. Databricks Runtime (DBR) already comes with specific versions of</p><ul><li>NumPy</li><li>Pandas</li><li>PyArrow</li></ul><p>If your wheel forces different versions — especially NumPy 2.x — you can break the entire cluster Python environment.</p><p><strong>Golden Rule</strong></p><p>Never force core data stack versions unless absolutely required.</p><p>Avoid pinning numpy, pandas, pyarrow, ipython</p><p>Unless you are 100% sure they match the DBR runtime. Let Databricks manage its own core libraries.</p><p><strong>Step 5: Inspect the Actual Runtime Environment</strong></p><p>When things behave strangely, inspect the environment directly</p><pre>import sys<br>print(sys.executable)<br>print(sys.version)<br>print(sys.path)</pre><p>This tells you:</p><ul><li>Which Python executable is running</li><li>Which version</li><li>Where site-packages are loaded from</li></ul><p>If your module path is not in sys.path, that’s your issue</p><p><strong>Step 6: Job Clusters Behave Differently</strong></p><p>All-purpose cluster</p><ul><li>Persistent environment</li><li>Easier to debug</li></ul><p>Job cluster</p><ul><li>Fresh environment every run</li><li>Libraries reinstalled each time</li><li>More strict isolation</li></ul><p>If it works interactively but fails in jobs, Check</p><ul><li>Whether the wheel is attached at job configuration level</li><li>Whether dependent wheels are also installed</li><li>Install order (dependency before dependent)</li></ul><p>When your wheel fails on Databricks, try run through this checklist:</p><pre>Debug Checklist<br><br>- [ ] Package installed on cluster<br>- [ ] Import works on driver<br>- [ ] Import works on executors<br>- [ ] Wheel contains all modules<br>- [ ] No conflicting NumPy / PyArrow versions<br>- [ ] sys.path includes your package<br>- [ ] Job cluster has libraries attached<br>- [ ] Dependencies installed in correct order</pre><h3><strong>Commands</strong></h3><pre># ============================================================<br># Field Commands You’ll Actually Use in Production (Databricks)<br># Wheel / dependency debugging playbook<br># Replace:<br>#   - &quot;your_package&quot;       -&gt; your import package (module) name<br>#   - &quot;your-package-name&quot;  -&gt; your wheel distribution name (pip name)<br># ============================================================<br><br># ------------------------------------------------------------<br># 0) Quick environment fingerprint (driver)<br># ------------------------------------------------------------<br>import sys<br>print(&quot;PYTHON EXECUTABLE:&quot;, sys.executable)<br>print(&quot;PYTHON VERSION:&quot;, sys.version)<br><br>print(&quot;\nPYTHON PATH (driver):&quot;)<br>for p in sys.path:<br>    print(&quot; -&quot;, p)<br><br><br># ------------------------------------------------------------<br># 1) Verify your package is importable (driver)<br># ------------------------------------------------------------<br>import importlib.util<br># None =&gt; not visible<br>print(&quot;FIND_SPEC your_package:&quot;, importlib.util.find_spec(&quot;your_package&quot;))  <br><br><br><br># ------------------------------------------------------------<br># 2) Print the package file location (driver)<br># ------------------------------------------------------------<br># (Only works if import succeeds)<br>try:<br>    import your_package<br>    print(&quot;your_package.__file__:&quot;, your_package.__file__)<br>except Exception as e:<br>    print(&quot;IMPORT FAILED (driver):&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 3) Inspect wheel metadata + list packaged files (driver)<br># (Catches: wheel built without submodules)<br># ------------------------------------------------------------<br>try:<br>    import importlib_metadata as md<br>    dist = md.distribution(&quot;your-package-name&quot;)<br>    print(&quot;DIST VERSION:&quot;, dist.version)<br><br>    print(&quot;\nFILES IN WHEEL (first 200):&quot;)<br>    for i, f in enumerate(dist.files or []):<br>        if i &gt;= 200:<br>            print(&quot;... (truncated)&quot;)<br>            break<br>        print(&quot; -&quot;, f)<br><br>    # Optional: filter for interesting filenames<br>    print(&quot;\nFILTERED FILES (match: enrich/core/rest/main):&quot;)<br>    for f in (dist.files or []):<br>        s = str(f).lower()<br>        if (&quot;enrich&quot; in s) or (&quot;core&quot; in s) or (&quot;test&quot; in s) or (&quot;main&quot; in s):<br>            print(&quot; -&quot;, f)<br><br>except Exception as e:<br>    print(&quot;DIST METADATA FAILED:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 4) Verify executors can import your package<br># (Most important: if this fails, Spark workers can&#39;t see the wheel)<br># ------------------------------------------------------------<br>try:<br>    ok = spark.sparkContext.parallelize([1], 1).map(<br>        lambda _: __import__(&quot;your_package&quot;).__name__   # return a string (serializable)<br>    ).collect()<br>    print(&quot;EXECUTOR IMPORT OK:&quot;, ok)<br>except Exception as e:<br>    print(&quot;EXECUTOR IMPORT FAILED:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 5) Compare driver vs executor Python (version + executable)<br># (Useful when environments differ)<br># ------------------------------------------------------------<br>try:<br>    ex = spark.sparkContext.parallelize([1], 1).map(<br>        lambda _: (__import__(&quot;sys&quot;).executable, __import__(&quot;sys&quot;).version)<br>    ).collect()<br>    print(&quot;EXECUTOR PYTHON INFO:&quot;, ex)<br>except Exception as e:<br>    print(&quot;EXECUTOR PYTHON INFO FAILED:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 6) Inspect executor sys.path (package visibility)<br># ------------------------------------------------------------<br>try:<br>    paths = spark.sparkContext.parallelize([1], 1).map(<br>        lambda _: __import__(&quot;sys&quot;).path<br>    ).collect()<br>    print(&quot;EXECUTOR sys.path (first 25 entries):&quot;)<br>    for p in paths[0][:25]:<br>        print(&quot; -&quot;, p)<br>except Exception as e:<br>    print(&quot;EXECUTOR sys.path FAILED:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 7) Smoke test distributed pandas execution (mapInPandas-style)<br># (Ensures imports work in vectorized/distributed pandas context)<br># ------------------------------------------------------------<br>import pandas as pd<br><br>def _import_smoke_test(iterator):<br>    import pandas as pd<br>    # Try importing your package inside worker-side pandas code<br>    import your_package  # replace<br>    for _pdf in iterator:<br>        yield pd.DataFrame({&quot;ok&quot;: [1]})<br><br>try:<br>    spark.range(1).mapInPandas(_import_smoke_test, &quot;ok long&quot;).show()<br>except Exception as e:<br>    print(&quot;mapInPandas import smoke test FAILED:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 8) Check core stack versions (NumPy / Pandas / PyArrow)<br># (ABI mismatch issues show up here)<br># ------------------------------------------------------------<br>try:<br>    import numpy<br>    print(&quot;NumPy :&quot;, numpy.__version__)<br>except Exception as e:<br>    print(&quot;NumPy import failed:&quot;, repr(e))<br><br>try:<br>    import pandas<br>    print(&quot;Pandas:&quot;, pandas.__version__)<br>except Exception as e:<br>    print(&quot;Pandas import failed:&quot;, repr(e))<br><br>try:<br>    import pyarrow<br>    print(&quot;PyArrow:&quot;, pyarrow.__version__)<br>except Exception as e:<br>    print(&quot;PyArrow import failed:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 9) Databricks Runtime version (DBR)<br># ------------------------------------------------------------<br>try:<br>    print(&quot;DBR VERSION:&quot;, spark.conf.get(&quot;spark.databricks.clusterUsageTags.sparkVersion&quot;))<br>except Exception as e:<br>    print(&quot;DBR VERSION lookup failed:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 10) Site-packages locations (driver)<br># ------------------------------------------------------------<br>try:<br>    import site<br>    print(&quot;SITE PACKAGES (driver):&quot;)<br>    for p in site.getsitepackages():<br>        print(&quot; -&quot;, p)<br>except Exception as e:<br>    print(&quot;site.getsitepackages() failed:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 11) List console entry points (driver)<br># (If your wheel exposes a CLI entry point)<br># ------------------------------------------------------------<br>try:<br>    import importlib_metadata as md<br>    eps = md.entry_points()<br>    <br>    for ep in eps.select(group=&quot;console_scripts&quot;):<br>        print(ep.name, &quot;-&gt;&quot;, ep.value)<br>except Exception as e:<br>    print(&quot;Entry points listing failed:&quot;, repr(e))<br><br><br># ------------------------------------------------------------<br># 12) Notebook-only commands (run as separate cells)<br># (These are valid Databricks notebook magics)<br># ------------------------------------------------------------<br># %pip list | grep your-package-name<br># %pip show -f your-package-name<br># %pip install --force-reinstall /dbfs/path/to/your_wheel.whl<br># %pip cache purge</pre><h3>Final Thought</h3><p>The biggest misconception in data engineering pipelines is:</p><blockquote><em>“If it works locally, it should work in Spark.”</em></blockquote><p>It won’t.</p><p>Because you are no longer running one Python process.</p><p>You are running <strong>distributed Python environments across multiple nodes</strong>.</p><p>And once you understand that, debugging stops being guesswork and becomes systematic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fda4702b8ede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why DROP COLUMN in Databricks Delta Lake Doesn’t Do What You Expect]]></title>
            <link>https://rknutalapati.medium.com/why-drop-column-in-databricks-delta-lake-doesnt-do-what-you-expect-39be2ceb24df?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/39be2ceb24df</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 12:46:26 GMT</pubDate>
            <atom:updated>2025-12-11T12:59:32.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkCoGTUqFjrqeXFnDZDvng.png" /></figure><p>Have you ever dropped a column in Delta Lake and then noticed that your storage didn’t change? Or found that the old Parquet files still have the column you removed?</p><p>You’re not the only one. DROP COLUMN in Delta Lake can be confusing. Many people expect it to rewrite files and remove data right away, but that’s not what happens.</p><p>In this guide, we’ll walk through the whole process step by step. We’ll create a dataset, build an external Delta table with column mapping, drop a column, and then look at both the Delta log and the Parquet files to see what actually changes and what doesn’t.</p><p>By the end, you’ll clearly understand how DROP COLUMN works in Delta Lake and what you need to do if you want the column removed from disk, not just from the schema.</p><h3>1. Creating an External Delta Table (with Column Mapping Enabled)</h3><p>Delta Lake needs <strong>column mapping</strong> enabled before you can drop or rename columns safely. This feature gives each column a stable ID, so schema changes don’t get mixed up with physical Parquet file layouts.</p><pre>external_path = &quot;&lt;path to the data&gt;/events.delta&quot;<br>spark.sql(f&quot;&quot;&quot;<br>            CREATE TABLE IF NOT EXISTS qa.log_db.events (<br>                event_id BIGINT,<br>                user_id INT,<br>                event_type STRING,<br>                event_timestamp TIMESTAMP,<br>                ip_address STRING<br>            )<br>            USING DELTA<br>            LOCATION &#39;{external_path}&#39;<br>            TBLPROPERTIES (&#39;delta.columnMapping.mode&#39; = &#39;name&#39;)<br>        &quot;&quot;&quot;)</pre><h3>2. Generating a Large Synthetic Dataset</h3><pre>from pyspark.sql import functions as F<br><br>table_name = events<br>num_rows = 100_000_000<br>external_path = &quot;&lt;path to the data&gt;/events.delta&quot;<br><br>df = (<br>    spark.range(num_rows)<br>         .withColumn(&quot;event_id&quot;, F.col(&quot;id&quot;))<br>         .withColumn(&quot;user_id&quot;, F.expr(&quot;cast(rand()*1000000 as int)&quot;))<br>         .withColumn(&quot;event_type&quot;, F.expr(&quot;case when rand() &lt; 0.5 then &#39;click&#39; else &#39;view&#39; end&quot;))<br>         .withColumn(&quot;event_timestamp&quot;, F.current_timestamp())<br>         .withColumn(<br>             &quot;ip_address&quot;,<br>             F.concat(<br>                 F.expr(&quot;cast(rand()*255 as int)&quot;), F.lit(&quot;.&quot;),<br>                 F.expr(&quot;cast(rand()*255 as int)&quot;), F.lit(&quot;.&quot;),<br>                 F.expr(&quot;cast(rand()*255 as int)&quot;), F.lit(&quot;.&quot;),<br>                 F.expr(&quot;cast(rand()*255 as int)&quot;)<br>             )<br>         )<br>         .repartition(400)<br>)<br><br>df.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(external_path)<br><br></pre><h3>3. DROP COLUMN Updates Only Metadata</h3><p>Let’s drop a column:</p><pre>ALTER TABLE events DROP COLUMNS (ip_address);</pre><p>What this does:</p><ul><li>Updates the schema stored inside the Delta log</li><li>Removes the fields from the table’s schema</li><li>Finishes almost instantly</li></ul><p>What it <strong>does not</strong> do:</p><ul><li>Rewrite Parquet files</li><li>Remove data from disk</li><li>Save storage</li></ul><p>After the drop, the table <em>logically</em> has a new schema, but the old files are still sitting on disk with the original fields.</p><h3>Delta Log Before vs. After DROP COLUMN</h3><h4>Before</h4><p>List the Delta logs:</p><pre>display(dbutils.fs.ls(&#39;abfss://&lt;your storage path&gt;/_delta_log/&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*OMa6G8FYr7gPZ50GhU3Avg.png" /></figure><p>Check the schema stored in commit JSON:</p><pre>from pyspark.sql.functions import *<br>from pyspark.sql.types import *<br><br>from pyspark.sql.functions import col<br><br>log_path = &#39;abfss://****REDACTED****/_delta_log/00000000000000000001.json&#39;<br>df_raw = spark.read.json(f&quot;{log_path}&quot;)<br> <br>df_raw.filter(col(&quot;metaData&quot;).isNotNull()) \<br>    .select(col(&quot;metaData&quot;) .alias(&quot;metaDatainfo&quot;)) \<br>    .select(&quot;metaDatainfo.schemaString&quot;)  \<br>    .display()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*RWUN_JMfyADC9BST6R9hLA.png" /></figure><h4>After</h4><p>Now inspect the <em>next</em> commit (version increases by 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*4SWszieqz8jRIKY0rPA8tw.png" /></figure><p>You will see that the schema was updated — the <em>ip_address</em> field is no longer listed. Again, this is <em>only</em> a metadata change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*byNJMH6X8zSL3fblJn5mOA.png" /></figure><h4>Inspecting Parquet Files After the Drop</h4><p>Spark won’t let you read a Parquet file directly from a Delta table folder because of the _delta_log. Copy the files to another folder so you can inspect them as plain Parquet.</p><pre>import time<br>from pyspark.sql import functions as F<br><br>src_folder = &quot;abfss://&lt;container&gt;@&lt;storage&gt;.dfs.core.windows.net/events.delta&quot;<br>dst_folder = &quot;abfss://&lt;container&gt;@&lt;storage&gt;.dfs.core.windows.net/events_droptest&quot;<br><br># Use a timestamp prefix so multiple runs don&#39;t collide<br>run_id = int(time.time())<br>prefix = f&quot;droptest_{run_id}_&quot;<br><br># Create the destination folder if it doesn&#39;t exist<br>try:<br>    dbutils.fs.ls(dst_folder)<br>except:<br>    dbutils.fs.mkdirs(dst_folder)<br><br># Pick the first five parquet data files from the source folder<br>files = [<br>    f.path for f in dbutils.fs.ls(src_folder)<br>    if f.path.lower().endswith(&quot;.parquet&quot;) or &quot;part-&quot; in f.path.lower()<br>]<br><br>files_to_copy = sorted(files)[:5]<br><br>print(f&quot;Copying {len(files_to_copy)} files to {dst_folder}...\n&quot;)<br><br>for src_path in files_to_copy:<br>    filename = src_path.split(&quot;/&quot;)[-1]<br>    dest_path = f&quot;{dst_folder}/{prefix}{filename}&quot;<br><br>    # Delete if already present  <br>    dbutils.fs.rm(dest_path, recurse=False)<br><br>    print(f&quot;  {filename}&quot;)<br>    dbutils.fs.cp(src_path, dest_path)<br><br>print(&quot;\nDone.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhwHbsCImhzs6yuOnOyPsA.png" /></figure><h4>Next Step: Insert New Data and Compare Schemas</h4><p>After reviewing the older Parquet files, insert a few new rows into the table</p><pre>INSERT INTO events VALUES (999999999, 42, &#39;click&#39;, current_timestamp());</pre><p>Then inspect the most recent Parquet files (copy them the same way as above). You’ll notice</p><ul><li><strong>Old Parquet files</strong> still contain the dropped column</li><li><strong>New Parquet files</strong> do not</li></ul><p>This side-by-side comparison makes the DROP COLUMN behavior clear:</p><h3>4. The Dropped Columns Still Exist Physically</h3><p>Even though the schema has changed, the older Parquet files still carry <em>ip_address</em>. New files written afterward will not include those fields.</p><p>Delta handles this quietly. Readers use the schema from the Delta log, not the physical file layout, so you won’t notice anything during a normal query.</p><h3>5. Does OPTIMIZE Remove Dropped Columns?</h3><p>A common assumption is that OPTIMIZE “cleans up” columns that were dropped. It doesn’t.</p><pre>OPTIMIZE events;</pre><p>OPTIMIZE:</p><ul><li>Compacts many small files into larger ones</li><li>Reduces file count</li><li>Improves read speeds</li></ul><p>But it still rewrites files using their <strong>original physical schema</strong>, so the dropped columns remain inside the new files.</p><p>If you open the Parquet files directly, the old columns are still there. Delta just ignores them.</p><h3>6. How to Physically Remove a Dropped Column</h3><p>To actually remove the data from disk, you must <strong>rewrite</strong> the table using the updated schema.</p><h3>Option 1 — CTAS</h3><pre>CREATE OR REPLACE TABLE events_rewritten<br>USING DELTA<br>LOCATION &#39;&lt;your location&gt;&#39;<br>AS<br>SELECT event_id, user_id, event_type, event_timestamp<br>FROM events;</pre><h3>Option 2 — Overwrite the Table</h3><pre>df_clean = spark.table(&quot;events&quot;).select(<br>    &quot;event_id&quot;, &quot;user_id&quot;, &quot;event_type&quot;, &quot;event_timestamp&quot;<br>)<br><br>df_clean.write.format(&quot;delta&quot;) \<br>       .mode(&quot;overwrite&quot;) \<br>       .option(&quot;overwriteSchema&quot;, &quot;true&quot;) \<br>       .saveAsTable(&quot;events&quot;)</pre><h3>Then vacuum the old files</h3><pre>VACUUM events RETAIN 168 HOURS;</pre><p>Only after a rewrite + vacuum will the old Parquet files (and the dropped columns) disappear.</p><h3>7. Things to Keep in Mind</h3><ul><li>DROP COLUMN does not reduce storage.</li><li>PII removal requires a full rewrite + VACUUM.</li><li>OPTIMIZE does not modify the physical schema.</li><li>Plan rewrites during low-traffic windows.</li><li>Mixed physical schema files are normal and fully supported.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39be2ceb24df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Dictionaries: Collision Handling vs Duplicate Keys]]></title>
            <link>https://rknutalapati.medium.com/python-dictionaries-collision-handling-vs-duplicate-keys-fd315ed5a186?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd315ed5a186</guid>
            <category><![CDATA[python-dictionaries]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-programming-tips]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 19:25:44 GMT</pubDate>
            <atom:updated>2025-09-27T19:25:44.068Z</atom:updated>
            <content:encoded><![CDATA[<p>Python dictionaries are one of the most powerful data structures in the language. They are fast, flexible, and widely used in everyday programming. But understanding what happens behind the scenes — especially with <strong>duplicate keys</strong> and <strong>hash collisions</strong> — can help you write more efficient and reliable code.</p><p>Two concepts that often confuse beginners are:</p><ul><li><strong>Duplicate keys</strong> — what happens if the same key is inserted more than once?</li><li><strong>Collisions</strong> — what happens if two different keys produce the same hash?</li></ul><p>Although they sound similar, Python handles them very differently. This article explains both with examples, visuals, and practical insights.</p><h4>How Dictionaries Work</h4><p>At their core, Python dictionaries are <strong>hash tables</strong>:</p><ul><li>Each key is passed through Python’s built-in hash() function.</li><li>The hash determines the <strong>bucket</strong> where the key-value pair will be stored.</li><li>Retrieval uses the hash to jump directly to the slot, making lookups very fast (average O(1) time complexity).</li></ul><p>But how does Python handle duplicate keys or collisions in the same bucket? Let’s explore.</p><h4>Duplicate Keys: Overwriting Behavior</h4><p>Python dictionaries <strong>do not allow multiple copies of the same key</strong>. If you insert a key twice, the new value simply overwrites the old one.</p><pre>  <br>fruit_counts = {&quot;apple&quot;: 10, &quot;banana&quot;: 5}<br>fruit_counts[&quot;apple&quot;] = 20  # Duplicate key<br> <br>print(fruit_counts)<br></pre><p><strong>Explanation:</strong></p><ul><li>Only one “apple” key remains.</li><li>This is <strong>not a collision</strong>; Python never allows duplicate keys.</li></ul><p><strong>Visual Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cXvtw7WJl16PLJzWAbWp6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_VDjM03JjdcUiUWRBgpJew.png" /></figure><p>Key takeaway: <strong>Duplicates overwrite old values.</strong></p><h4>Collisions: Different Keys, Same Hash</h4><p>Collisions occur when <strong>two different keys</strong> produce the same hash. Python handles this elegantly using <strong>probing + equality checks</strong>.</p><p>Here’s an example with a custom class:</p><pre># Exercise 2: Hash collision with custom objects<br>class CollideExample:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def __hash__(self):<br>        return 100  # Force all objects to same hash<br><br>    def __eq__(self, other):<br>        return isinstance(other, CollideExample) and self.name == other.name<br><br>a = CollideExample(&quot;A&quot;)<br>b = CollideExample(&quot;B&quot;)<br>c = CollideExample(&quot;C&quot;)<br><br>my_dict = {a: &quot;Value A&quot;, b: &quot;Value B&quot;, c: &quot;Value C&quot;}<br>print(my_dict)<br></pre><pre># Out Put<br>{<br> &lt;__main__.CollideExample object at 0x000002A85497BDF0&gt;: &#39;Value A&#39;, <br> &lt;__main__.CollideExample object at 0x000002A85497BD90&gt;: &#39;Value B&#39;, <br> &lt;__main__.CollideExample object at 0x000002A85497BA60&gt;: &#39;Value C&#39;<br>}</pre><p>Even though all three objects have the same hash, Python stores <strong>each key separately</strong> because a != b != c.</p><p><strong>__hash__ explanation:</strong></p><ul><li>Every object in Python has a __hash__ method that returns an integer.</li><li>This integer is used by dictionaries and sets to quickly locate items.</li><li>For example, hash(“apple”) returns an integer that determines its bucket.</li><li>Equality checks (__eq__) determine if two keys are considered the same.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lef_UibLACIuq8qYh-_L9A.png" /></figure><h4>Duplicate vs Collision: Quick Comparison</h4><pre>+----------------+-------------------------------=+----------------------------+------------------------+<br>| Case           | Behavior                       | Example                    | Visual                 |<br>+----------------+--------------------------------+----------------------------+------------------------+<br>| Duplicate Key  | Old value is replaced          | &quot;apple&quot;:10 -&gt; &quot;apple&quot;:20   | Single slot updated    |<br>| Collision      | Multiple keys in same bucket   | a:100, b:100               | Both keys in bucket    |<br>+----------------+--------------------------------+----------------------------+------------------------+</pre><h4>Why This Matters</h4><ul><li><strong>Performance</strong>: Collisions increase the number of lookups, slightly slowing dictionary operations.</li><li><strong>Custom Objects</strong>: Bad __hash__ implementations can cause excessive collisions.</li><li><strong>Security</strong>: Hash collisions are a known attack vector (hash flooding), mitigated by Python’s hash randomization.</li></ul><h4>Tips</h4><ul><li>Always use <strong>immutable types</strong> as dictionary keys (strings, numbers, tuples).</li><li>Implement __hash__ and __eq__ properly for custom objects.</li><li>Avoid forcing many keys to the same hash unless you’re experimenting.</li></ul><h3>Conclusion</h3><p>In Python dictionaries:</p><ul><li><strong>Duplicate keys</strong> overwrite previous values.</li><li><strong>Collisions </strong>occur when multiple keys hash to the same bucket. They are resolved by finding an alternative position in the hash table (using probing) and performing equality checks to ensure the correct key is accessed.</li></ul><p>Understanding this distinction can help you design <strong>efficient, reliable, and secure Python applications</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd315ed5a186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimized Approach to Many-to-Many Joins with LATERAL VIEW in Databricks Spark SQL]]></title>
            <link>https://rknutalapati.medium.com/optimized-approach-to-many-to-many-joins-with-lateral-view-in-databricks-spark-sql-6b146b9c6d8a?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b146b9c6d8a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 20:33:18 GMT</pubDate>
            <atom:updated>2025-09-26T20:33:18.296Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Many-to-many relationships frequently arise in data processing workflows for example, when multiple items are related to multiple categories, or users belong to multiple groups. Efficiently handling these relationships is essential for maintaining performance and scalability, especially in large-scale distributed systems like Databricks.</p><p>This blog explores a common scenario involving assignment of entities based on grouped associations. It demonstrates how to use Spark SQL functions such as collect_list and LATERAL VIEW explode to manage many-to-many joins effectively, reducing data duplication and shuffle overhead.</p><p>By following this example, you will learn a practical approach to optimize joins in Databricks SQL and improve query performance in pipelines that deal with complex relational data.</p><h3>Scenario: Assigning Orders to Addresses within Zones</h3><p>Consider a dataset where:</p><ul><li>Each order is assigned to a zone.</li><li>Each zone includes multiple addresses.</li><li>Each address has an associated load metric (e.g., capacity, priority).</li><li>The goal is to assign each order to one address in its zone with the lowest load.</li></ul><p>This is a typical many-to-many mapping challenge, where orders relate to zones, and zones relate to multiple addresses.</p><h3>Synthetic Data Generation</h3><p>Let’s create synthetic tables to simulate a scenario where orders must be assigned to addresses within a zone. Each order comes with a zone ID, and each zone maps to several addresses.</p><pre>-- 1.0 Orders Table  <br>CREATE OR REPLACE TEMP VIEW orders_vw AS<br>SELECT<br>  CONCAT(&#39;O&#39;, CAST(id AS STRING)) AS OrderId,<br>  CONCAT(&#39;Z&#39;, CAST(id % 100 AS STRING)) AS ZoneId,<br>  CONCAT(&#39;C&#39;, CAST(id % 50000 AS STRING)) AS CustId<br>FROM RANGE(1000000);</pre><pre>-- 2.0 Zone Address Load Table (1000 zones × 15 addresses each)<br>-- increase the zones and addresses for testing<br>CREATE OR REPLACE TEMP VIEW zone_addresses_load_vw AS<br>WITH zones AS (<br>  SELECT CONCAT(&#39;Z&#39;, CAST(id AS STRING)) AS ZoneId FROM RANGE(1000)<br>),<br>addresses AS (<br>  SELECT CONCAT(&#39;A&#39;, CAST(id AS STRING)) AS AddressLabel FROM RANGE(15)<br>)<br>SELECT<br>  z.ZoneID,<br>  CONCAT(z.ZoneID, &#39;_&#39;, a.AddressLabel) AS AddressId,<br>  CAST((RAND() * 10 + 1) AS INT) AS CurrentLoad<br>FROM zones z<br>CROSS JOIN addresses a;<br><br>-- 3.0 Drop and Create tables<br>DROP TABLE IF EXISTS &lt;DataBaseName&gt;.orders;<br>DROP TABLE IF EXISTS &lt;DataBaseName&gt;.zone_addresses_load;<br> <br>CREATE TABLE IF NOT EXISTS &lt;DataBaseName&gt;.orders AS<br>SELECT<br>   *<br>FROM orders_vw;<br><br>CREATE TABLE IF NOT EXISTS &lt;DataBaseName&gt;.zone_addresses_load AS<br>SELECT<br>   *<br>FROM zone_addresses_load_vw;</pre><h3><strong>The Naive Approach: Direct Join on Many-to-Many Keys</strong></h3><p>A straightforward solution is to join orders with addresses on zone -</p><pre>-- 1. Compute total load per zone<br>CREATE OR REPLACE TEMP VIEW zone_total_load AS<br>SELECT<br>  ZoneID,<br>  SUM(CurrentLoad) AS TotalZoneLoad<br>FROM zone_addresses_load<br>GROUP BY ZoneID;</pre><pre>-- 1.1<br>CREATE OR REPLACE TEMP VIEW naive_order_address_filtered_qualify AS<br>SELECT<br>  o.OrderID,<br>  o.ZoneID,<br>  o.CustID,<br>  z.AddressID,<br>  z.CurrentLoad,<br>  t.TotalZoneLoad<br>FROM orders o<br>JOIN zone_addresses_load z<br>  ON o.ZoneID = z.ZoneID<br>JOIN zone_total_load t<br>  ON z.ZoneID = t.ZoneID<br>WHERE t.TotalZoneLoad &gt; 50<br>QUALIFY ROW_NUMBER() OVER (PARTITION BY o.OrderID ORDER BY z.CurrentLoad) = 1;</pre><blockquote><strong>Note:</strong> While <em>QUALIFY </em>simplifies the SQL query by allowing direct filtering on window function results, it does not reduce the data explosion or shuffle overhead caused by the many-to-many join itself. The join still generates a large intermediate dataset causing increased query latency, especially when ranking or filtering is applied after the join.</blockquote><h3><strong>Alternate approach with Spark Functions — collect_list + LATERAL VIEW explode</strong></h3><pre>-- 2.0<br>CREATE OR REPLACE TEMP VIEW zone_address_list AS<br>SELECT<br>  ZoneID,<br>  COLLECT_LIST(NAMED_STRUCT(&#39;AddressID&#39;, AddressID, &#39;CurrentLoad&#39;, CurrentLoad)) AS AddressOptions,<br>  COUNT(*) AS NumAddresses,<br>  SUM(CurrentLoad) AS TotalZoneLoad,<br>  ROUND(AVG(CurrentLoad), 2) AS AvgZoneLoad<br>FROM zone_addresses_load<br>GROUP BY ZoneID;</pre><p>We now join orders to pre-aggregated zone data, and then explode only for zones with meaningful load.</p><pre>-- 2.1<br>CREATE OR REPLACE TEMP VIEW order_address_exploded AS<br>SELECT<br>  o.OrderID,<br>  o.ZoneID,<br>  o.CustID,<br>  a.AddressID,<br>  a.CurrentLoad,<br>  z.TotalZoneLoad,<br>  z.AvgZoneLoad,<br>  ROW_NUMBER() OVER (PARTITION BY o.OrderID ORDER BY a.CurrentLoad ASC) AS rn<br>FROM orders o<br>JOIN zone_address_list z<br>  ON o.ZoneID = z.ZoneID<br>LATERAL VIEW EXPLODE(z.AddressOptions) AS a<br>WHERE z.TotalZoneLoad &gt; 50;</pre><h3>Final Thoughts</h3><p>This approach showcases how array aggregation and EXPLODE via LATERAL VIEW can prevent data bloat from naive many-to-many joins. It combines SQL expressiveness with Spark’s distributed power, all while staying performant.</p><p>Filtering the naive join based on aggregated metrics (like total zone load) can reduce the data explosion somewhat, and QUALIFY can simplify query syntax, but the join size and shuffle remain large.</p><blockquote><strong><em>Note:</em></strong><em> The scenario presented in this blog is a </em><strong><em>synthetic example</em></strong><em> designed to highlight different approaches to handling many-to-many joins. In real-world pipelines, the structure of data and business rules might require alternate strategies based on system constraints, SLA needs, or update patterns. Always profile with your actual datasets before choosing a pattern.</em></blockquote><p>Got a better pattern? I’d love to hear it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b146b9c6d8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spark’s Catalyst Optimizer Improves SQL IN Clause Performance]]></title>
            <link>https://rknutalapati.medium.com/dont-just-use-in-how-spark-s-catalyst-supercharges-it-f824a9314e43?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/f824a9314e43</guid>
            <category><![CDATA[sql-optimization]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 22:49:42 GMT</pubDate>
            <atom:updated>2025-08-27T16:14:07.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIXyTU8PK5MsxTPW3YyxNw.png" /></figure><p>From IN to O(1) lookups — the hidden performance trick in Spark</p><h4>Introduction</h4><p>Have you ever wondered what really happens behind the scenes when you write a simple <strong>IN</strong> clause? Is Spark scanning every row? Is it checking against each item in the list one by one? Not quite.</p><p>The “IN” clause is one of the most widely used SQL constructs — and in Spark, it plays a surprisingly intelligent role. Depending on the structure of the list or subquery.</p><p>Spark’s Catalyst optimizer can eighter:</p><ol><li>Rewrite the <strong>IN </strong>predicate into an internal <strong>InSet</strong> representation, enabling a highly efficient, constant-time hash-based lookup instead of a linear search.</li><li>Transform <strong>IN</strong> into a <strong>Left Semi Join</strong> when the lookup comes from another table or dynamic source.</li></ol><p>Let’s explore both scenarios using an example dataset.</p><p>Example Dataset:</p><p>Imagine we have a master customers table and an hourly service log received as JSON messages via an API. We want to filter the customers who received a service.</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import lit, concat, col<br>import json<br><br>spark = SparkSession.builder.appName(&quot;SyntheticCustomers&quot;).getOrCreate()<br><br># Customer IDs from 100 to 10000<br>customer_ids = list(range(100, 10001))<br><br>customers_df = spark.createDataFrame(customer_ids, &quot;int&quot;).toDF(&quot;customer_id&quot;)<br><br># Add first_name, last_name, and email<br>customers_df = customers_df.withColumn(&quot;first_name&quot;, concat(lit(&quot;FirstName_&quot;), col(&quot;customer_id&quot;))) \<br>                           .withColumn(&quot;last_name&quot;, concat(lit(&quot;LastName_&quot;), col(&quot;customer_id&quot;))) \<br>                           .withColumn(&quot;email&quot;, concat(col(&quot;first_name&quot;), lit(&quot;.&quot;), col(&quot;last_name&quot;), lit(&quot;@example.com&quot;)))<br><br># Show sample<br># customers_df.show(10)</pre><h4>Example 1 — IN Predicate</h4><p>Here, we parse a small list of customers from the API and filter the master table</p><pre>api_json_message = &quot;&quot;&quot;<br>{<br>  &quot;batch_timestamp&quot;: &quot;2025-08-13T10:00:00Z&quot;,<br>  &quot;location_id&quot;: 501,<br>  &quot;service_type&quot;: &quot;FullService&quot;,<br>  &quot;service_customer_ids&quot;: [101, 102, 105, 102, 105, 108, 109, 110, 111],<br>  &quot;processed_by&quot;: &quot;service_sync_job&quot;,<br>  &quot;source_system&quot;: &quot;ServiceCenterApp&quot;<br>}<br>&quot;&quot;&quot;<br><br># Parse JSON string into Python dict<br>api_json_dict = [json.loads(api_json_message)]   <br><br># Create DataFrame directly<br>json_df = spark.createDataFrame(api_json_dict)<br>json_df.show()<br><br># Extract service_customer_ids list<br>service_customer_ids = json_df.first()[&quot;service_customer_ids&quot;]<br>customers_df = spark.read.table(&quot;customers_master_data&quot;)<br>result_df = customers_df.filter(col(&quot;customer_id&quot;).isin(service_customer_ids))<br># result_df.show()<br>result_df.explain(True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VbWyA6HfnYU_YNVVUap5g.png" /></figure><p>In this case, Catalyst does not use INSET. Why?</p><h4><strong>Example 2 — IN Predicate(InSet Optimization)</strong></h4><p>Now, let’s look at a slightly larger list</p><pre>api_json_message = &quot;&quot;&quot;<br>{<br>  &quot;batch_timestamp&quot;: &quot;2025-08-13T11:00:00Z&quot;,<br>  &quot;location_id&quot;: 502,<br>  &quot;service_type&quot;: &quot;FullService&quot;,<br>  &quot;service_customer_ids&quot;: [101,102,105,102,105,108,109,110,111,899,245,789,123,145,176,176,189,500,550,551,null,null],<br>  &quot;processed_by&quot;: &quot;service_sync_job&quot;,<br>  &quot;source_system&quot;: &quot;ServiceCenterApp&quot;<br>}<br>&quot;&quot;&quot;<br><br># Parse JSON string into Python dict<br>api_json_dict = [json.loads(api_json_message)]  <br><br># Create DataFrame directly<br>json_df = spark.createDataFrame(api_json_dict)<br>json_df.show()<br><br># Extract service_customer_ids list<br>service_customer_ids = json_df.first()[&quot;service_customer_ids&quot;]<br>customers_df = spark.read.table(&quot;customers_master_data&quot;)<br>result_df_2 = customers_df.filter(col(&quot;customer_id&quot;).isin(service_customer_ids))<br># result_df_2.show()<br>result_df_2.explain(True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZRU3sAEnLQkuGp5e8wHrg.png" /></figure><p>This time, you’ll notice the optimized logical plan shows<strong> INSET</strong>. Why?</p><p>IN vs INSET — Catalyst’s Decision</p><p>Spark’s <strong>Catalyst optimizer</strong> decides whether to rewrite an IN clause into an INSET based on</p><ol><li>Are the values <strong>constant literals</strong> known at compile time.</li><li>How many values in the list?</li></ol><p>The Spark configuration that controls this behavior is</p><pre>spark.conf.get(&quot;spark.sql.optimizer.inSetConversionThreshold&quot;)</pre><ul><li>Default values is “10”</li><li>If the list contains more than <strong>10 </strong>values, Catalyst rewrites IN into an INSET, creating an internal <strong>hash set structure</strong>.</li><li><strong>Benefit:</strong> Each row lookup becomes <strong>O(1)</strong>, significantly faster than scanning or joining</li></ul><p>Example 3 — IN (Left Semi Join)</p><p>Now, let’s look at a example that filters using IN from subquery.</p><pre>api_json_message = &quot;&quot;&quot;<br>{<br>  &quot;batch_timestamp&quot;: &quot;2025-08-13T11:00:00Z&quot;,<br>  &quot;location_id&quot;: 502,<br>  &quot;service_type&quot;: &quot;FullService&quot;,<br>  &quot;service_customer_ids&quot;: [101,102,105,102,105,108,109,110,111,899,245,789,123,145,176,176,189,500,550,551],<br>  &quot;processed_by&quot;: &quot;service_sync_job&quot;,<br>  &quot;source_system&quot;: &quot;ServiceCenterApp&quot;<br>}<br>&quot;&quot;&quot;<br><br># Parse JSON string into Python dict<br>api_json_dict = [json.loads(api_json_message)]   <br><br># Create DataFrame directly<br>json_df = spark.createDataFrame(api_json_dict)<br>json_df.createOrReplaceTempView(&quot;json_df&quot;)<br><br>customers_api = json_df.select(explode(&quot;service_customer_ids&quot;).alias(&quot;customer_id&quot;))<br>customers_api.createOrReplaceTempView(&quot;customers_api&quot;)<br> <br>result_dynamic =  spark.sql(&quot;&quot;&quot;<br>SELECT * FROM customers_master_data<br>WHERE customer_id IN (SELECT customer_id FROM customers_api)<br>&quot;&quot;&quot;)<br><br>result_dynamic.explain(True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-unD87iq8k2cIC_qLhI6iQ.png" /></figure><p><strong>Observation:</strong> This time, Catalyst uses a <strong>Left Semi Join</strong> — because the input list comes from a <strong>dynamic subquery</strong>, not a compile-time constant list.</p><h4>Why It Matters</h4><p>Understanding this behavior can help you write high-performance Spark SQL</p><ul><li>Use literal lists of sufficient size to trigger INSET</li><li>Avoid dynamic lists when expecting INSET optimization — Spark may fall back to a semi-join.</li></ul><p>A small tweak in how you provide values can be the difference between a query that scans millions of rows and one that executes significantly faster through them in milliseconds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f824a9314e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Spark Constant Folding Explained: A Small Optimization With Big Performance Gains]]></title>
            <link>https://rknutalapati.medium.com/apache-spark-constant-folding-explained-a-small-optimization-with-big-performance-gains-46bbe146b3f4?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/46bbe146b3f4</guid>
            <category><![CDATA[spark-catalyst]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineer-skills]]></category>
            <category><![CDATA[spark-optimization]]></category>
            <category><![CDATA[apache-spark]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 14:11:55 GMT</pubDate>
            <atom:updated>2025-07-03T14:11:55.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tN1T8YZc6-4sOD0H0pbWcQ.png" /></figure><p>When writing SQL or DataFrame queries in Apache Spark like <em>SELECT 2+4</em>, do you ever wonder if Spark actually performs the addition at runtime? The short answer: it doesn’t. Welcome to constant folding, one of Spark’s simplest yet most powerful query optimizations.</p><p>In this post, we’ll break down:</p><ul><li>What constant folding is</li><li>How it helps Spark run faster</li><li>Examples using integers, strings, timestamps, and more</li><li>How to recognize full vs. partial folding in execution plans</li></ul><p>Whether you’re debugging a slow query or just want to understand Catalyst better, these examples will make it click.</p><p><strong>What Is Constant Folding?</strong></p><p>Constant folding is a compiler optimization that evaluates constant expressions at compile time instead of runtime. Spark’s Catalyst optimizer uses this to simplify your logical plan before any data is touched.</p><p><strong>Simple Example:</strong></p><pre>const_fold_df = spark.sql(&quot;SELECT 2 + 3 AS fold_expr&quot;)<br>const_fold_df.explain(extended=True)</pre><pre>== Optimized Logical Plan ==<br>Project [5 AS fold_expr#20]<br>+- OneRowRelation</pre><p>Spark doesn’t do math at runtime if it already knows the answer.</p><h3><strong>Full Constant Folding Examples</strong></h3><p>These queries are independent of data, so Spark folds them entirely before execution.</p><p><strong>1. Folded Integer Expression</strong></p><pre>fld_int = spark.sql(&quot;SELECT 10 + 5 AS fld_int_exp&quot;)<br>fld_int.explain(True)</pre><pre>== Optimized Logical Plan ==<br>Project [<strong>15</strong> AS fld_int_exp#436]<br>+- OneRowRelation</pre><p><strong>2. Folded String Concatenation</strong></p><pre>fld_str = spark.sql(&quot;&quot;&quot;<br>                   SELECT concat(&#39;Spark&#39;,&#39; SQL&#39;) AS fld_str_exp, <br>                          &#39;Hello&#39; || &#39; World!&#39; AS fld_str_exp2<br>                    &quot;&quot;&quot;)<br>fld_str.explain(True)</pre><pre>== Optimized Logical Plan ==<br>Project [<strong>Spark SQL</strong> AS fld_str_exp#488, <strong>Hello World!</strong> AS fld_str_exp2#489]<br>+- OneRowRelation</pre><p><strong>3. Folded Date and Timestamp Math</strong></p><pre>fld_dt_tst = spark.sql(&quot;&quot;&quot;<br>                        SELECT TIMESTAMP(&#39;2025-07-01 00:00:00&#39;) + INTERVAL 30 MINUTES AS fld_tst_exp,<br>                        DATE&#39;2025-07-01&#39; + 3 AS fld_dt_exp<br>                     &quot;&quot;&quot;)<br>fld_dt_tst.explain(True)</pre><pre>== Optimized Logical Plan ==<br>Project [2025-07-01 <strong>00:30:00</strong> AS fld_tst_exp#514, 2025-07-<strong>04</strong> AS fld_dt_exp#515]<br>+- OneRowRelation</pre><h3>Partial Folding</h3><p>Spark doesn’t officially define “partial folding” as a Catalyst rule, but we use the term here to describe expressions where constant parts (like literals) are folded, while dynamic elements (like column references) remain and are evaluated at runtime.</p><p><strong>Synthetic Data</strong>:</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import current_date<br>from datetime import datetime, timedelta<br>import random<br><br>data = []<br>regions = [&#39;East&#39;, &#39;West&#39;, &#39;North&#39;, &#39;South&#39;]<br>base_date = datetime(2025, 1, 1)<br><br>for i in range(1000):<br>    sale_price = round(random.uniform(10, 500), 2)<br>    store_region = random.choice(regions)<br>    sale_date = base_date + timedelta(days=random.randint(0, 365))<br>    data.append((sale_price, store_region, sale_date))<br><br>columns = [&#39;sale_price&#39;, &#39;store_region&#39;, &#39;sale_date&#39;]<br>df = spark.createDataFrame(data, columns)<br>df.createOrReplaceTempView(&quot;sales&quot;)</pre><p><strong>5. Constant + Varying Column</strong></p><pre>cnst_var = spark.sql(&quot;SELECT DATE&#39;2025-07-01&#39; + cast(id  as int) AS fld_adj_date FROM RANGE(5)&quot;)<br>cnst_var.explain(True)</pre><pre>== Optimized Logical Plan ==<br>Project [<strong>date_add</strong>(2025-07-01, cast(<strong>id</strong>#699L as int)) AS fld_adj_date#698]<br>+- Range (0, 5, step=1, splits=None)</pre><p>Even with the explicit CAST(id AS INT), Spark recognizes this as a deterministic and simple transformation, so it performs partial folding. The literal date is constant folded, but id remains dynamic — resulting in a partially folded date_add() expression.</p><p><strong>6. Example with Aggregation</strong></p><pre>df = spark.sql(&quot;&quot;&quot;<br>SELECT<br>  store_region,<br>  COUNT(*) AS sale_count,<br>  AVG(sale_price + 4.0) AS avg_net_revenue<br>FROM sales<br>GROUP BY store_region<br>&quot;&quot;&quot;)<br>df.explain(True)</pre><pre>== Optimized Logical Plan ==<br>Aggregate [store_region#547], [store_region#547, count(1) AS sale_count#713L, avg((sale_price#546 + <strong>4.0</strong>)) AS avg_net_revenue#714]</pre><p>Where is the constant folding?</p><ul><li>The constant 4.0 is directly visible in the aggregation expression avg((sale_price + 4.0))</li><li>This means Spark has folded the constant value 4.0 (not calculated at runtime; it’s a known constant).</li><li>But sale_price is dynamic per row, so the sum sale_price + 4.0 cannot be fully folded.</li></ul><h3><strong>No Folding: UDFs &amp; </strong>Non-deterministic</h3><p><strong>7. UDF Blocks Folding</strong></p><p>When using UDFs, Spark treats them as black boxes and cannot apply constant folding, even if the logic inside is constant.</p><pre>from pyspark.sql.functions import udf<br><br>@udf(&quot;int&quot;)<br>def non_fold_udf():<br>    return 2 + 3<br><br>df = spark.range(1).withColumn(&quot;folded&quot;, non_fold_udf())<br>df.explain(True)</pre><pre>Project [id#757L, pythonUDF0#765 AS folded#760]<br>+- BatchEvalPython [non_fold_udf()#756], [pythonUDF0#765]<br>   +- Range (0, 1, step=1, splits=Some(8))</pre><p>The plan includes BatchEvalPython, indicating a Python UDF is being executed — Spark must evaluate it at runtime.</p><p><strong>8. Non-deterministic expressions</strong></p><pre>fld_non_dtst = spark.sql(&quot;&quot;&quot;<br>                        SELECT rand() + 10 AS non_dtst<br>                        &quot;&quot;&quot;)<br>fld_non_dtst.explain(True)</pre><pre>== Optimized Logical Plan ==<br>Project [(rand(-8719759699446758747) + 10.0) AS non_dtst#785]<br>+- OneRowRelation</pre><ul><li>rand() is a volatile, non-deterministic function.</li><li>Even though 10 is a constant, the whole expression depends on runtime state, so Spark cannot fold it.</li></ul><h3>Final Thoughts</h3><p>Constant folding is like a tiny but powerful assistant in Spark’s Catalyst optimizer. By evaluating constant expressions at compile time, Spark avoids unnecessary computation at runtime.</p><p>Understanding this optimization helps you:</p><ul><li>Write more efficient and predictable queries</li><li>Identify when performance differences are due to subtle expression changes</li></ul><p>Whether you’re tuning queries or learning Catalyst internals, constant folding is one of those small optimizations that can make a big difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46bbe146b3f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Catalyst Optimizer in PySpark: Catalyst vs. Non-Catalyst Functions]]></title>
            <link>https://rknutalapati.medium.com/understanding-catalyst-optimizer-in-pyspark-catalyst-vs-non-catalyst-functions-48dd1c75d037?source=rss-577ca3361e21------2</link>
            <guid isPermaLink="false">https://medium.com/p/48dd1c75d037</guid>
            <category><![CDATA[catalyst-optimizer]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[apache-spark-tips]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[big-data-engineering]]></category>
            <dc:creator><![CDATA[Rama Krishna Nutalapati]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 02:52:42 GMT</pubDate>
            <atom:updated>2025-06-17T02:52:42.262Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Apache Spark’s Catalyst optimizer is one of its strongest features. It helps transform logical query plans into optimized physical plans. But did you know not all PySpark functions benefit from Catalyst optimizations?</p><p>In this blog, we’ll explore:</p><ul><li>What is Catalyst Optimizer?</li><li>Examples of Catalyst-supported and non-Catalyst-supported functions</li><li>Performance comparison using real code and execution plans in Databricks</li></ul><p>What is Catalyst?</p><p>Catalyst is Spark’s built-in query optimization engine. It performs a variety of optimizations behind the scenes to make your queries faster and more efficient — such as constant folding, predicate pushdown, and projection pruning.</p><p>While Catalyst itself is a deep and powerful framework, this blog won’t dive into its internals. Instead, we’ll focus on how using Catalyst-supported functions in PySpark can lead to better performance compared to non-Catalyst operations.</p><p>Catalyst-Supported Functions — Most built-in functions are Catalyst-optimized.</p><p>For example:</p><pre>from pyspark.sql.functions import col, upper<br>df = spark.createDataFrame([(&quot;databricks&quot;,), (&quot;spark&quot;,)], [&quot;medium&quot;])<br>df = df.withColumn(&quot;upper_word&quot;, upper(col(&quot;word&quot;)))<br>df.explain()</pre><p>Generate Sample Data:</p><p>Use the following code to generate a synthetic retail dataset with 5 million records. The dataset mimics real-world product attributes such as</p><ul><li><strong>brand</strong> (e.g., Nike, Adidas, Puma)</li><li><strong>category</strong> (e.g., Shoes, Apparel)</li><li><strong>product_color</strong> (varied casing to test normalization)</li><li><strong>price</strong> (randomized between $10 and $500)</li><li><strong>release_date</strong> (spread over ~3 years)</li><li><strong>stock_level</strong> (based on id and randomness)</li><li><strong>in_stock</strong> (derived boolean field)</li></ul><pre># Step - 1<br>from pyspark.sql.functions import expr, rand, round<br><br>brands = [&quot;Nike&quot;, &quot;Adidas&quot;, &quot;Puma&quot;, &quot;Reebok&quot;, &quot;New Balance&quot;]<br>categories = [&quot;Shoes&quot;, &quot;Apparel&quot;, &quot;Accessories&quot;]<br>colors = [&quot;red&quot;, &quot;Red&quot;, &quot;RED&quot;, &quot;blue&quot;, &quot;Blue&quot;, &quot;green&quot;, &quot;Green&quot;, &quot;yellow&quot;, &quot;Yellow&quot;, &quot;black&quot;, &quot;Black&quot;]<br><br>brands_expr = &quot;array(&quot; + &quot;, &quot;.join([f&quot;&#39;{b}&#39;&quot; for b in brands]) + &quot;)&quot;<br>categories_expr = &quot;array(&quot; + &quot;, &quot;.join([f&quot;&#39;{c}&#39;&quot; for c in categories]) + &quot;)&quot;<br>colors_expr = &quot;array(&quot; + &quot;, &quot;.join([f&quot;&#39;{c}&#39;&quot; for c in colors]) + &quot;)&quot;<br><br># Create data<br>df = (<br>    spark.range(5000000)<br>    .withColumn(&quot;brand&quot;, expr(f&quot;element_at({brands_expr}, cast((id % {len(brands)}) + 1 as INT))&quot;))<br>    .withColumn(&quot;category&quot;, expr(f&quot;element_at({categories_expr}, cast((id % {len(categories)}) + 1 as INT))&quot;))<br>    .withColumn(&quot;product_color&quot;, expr(f&quot;element_at({colors_expr}, cast((id % {len(colors)}) + 1 as INT))&quot;))<br>    .withColumn(&quot;price&quot;, round((rand(seed=42) * 490) + 10, 2)) <br>    .withColumn(&quot;release_date&quot;, expr(&quot;date_add(to_date(&#39;2022-01-01&#39;), cast((id % 1000) as INT))&quot;)) <br>    .withColumn(&quot;stock_level&quot;, expr(&quot;cast((id % 500 + rand(100) * 500) as INT)&quot;))  <br>    .withColumn(&quot;in_stock&quot;, expr(&quot;stock_level &gt; 0&quot;))<br>    .withColumn(&quot;color_list&quot;, expr(&quot;array(product_color, product_color, product_color)&quot;))<br>)<br><br># df.show(5, truncate=False)</pre><p>We’ll use this dataset to evaluate the performance of Catalyst-optimized vs. non-optimized operations in PySpark.</p><p>In the above dataset, standardize the <em>product_color </em>column and create a <em>product_tag </em>by concatenating the <em>brand</em>, <em>category</em>, and standardized color columns.</p><p>Non- Catalyst</p><pre>from pyspark.sql.functions import udf, col<br>from pyspark.sql.types import StringType<br>import time<br><br>@udf(StringType())<br>def build_tag(brand, category, color):<br>    return f&quot;{brand}-{category}-{color.upper()}&quot; if color else None<br>start = time.time()<br>df_udf = (<br>    df.withColumn(&quot;product_tag&quot;, build_tag(col(&quot;brand&quot;), col(&quot;category&quot;), col(&quot;product_color&quot;)))<br>)<br>df_udf.write.mode(&quot;overwrite&quot;).format(&quot;noop&quot;).save()<br>print(f&quot;UDF Version Time: {time.time() - start:.2f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*2wb_xWxNxZ22IaB9e3A1cg.png" /></figure><p>Why It’s not Optimized</p><ul><li><strong>Python UDF is a black box</strong>: Spark cannot introspect Python code inside a UDF.</li><li><strong>No Catalyst support</strong>: Catalyst cannot apply expression-level optimizations like pruning or folding.</li><li><strong>Serialization overhead</strong>: Data must be serialized between the JVM (Spark engine) and Python runtime.</li></ul><p>Catalyst-Optimized</p><pre>from pyspark.sql.functions import upper, concat_ws, col<br>import time<br><br>start = time.time()<br><br>df_catalyst = (<br>    df.withColumn(&quot;product_color_std&quot;, upper(col(&quot;product_color&quot;)))<br>      .withColumn(&quot;product_tag&quot;, concat_ws(&quot;-&quot;, col(&quot;brand&quot;), col(&quot;category&quot;), col(&quot;product_color_std&quot;)))<br>)<br><br>df_catalyst.write.mode(&quot;overwrite&quot;).format(&quot;noop&quot;).save()   <br>print(f&quot;Catalyst Version Time: {time.time() - start:.2f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1sGsNesNYJcnIM4BOE2ZA.png" /></figure><p>Why It’s Optimized</p><ul><li>All transformations use built-in functions</li><li>Functions like <em>upper()</em> and <em>concat_ws()</em> are recognized by Catalyst, allowing Spark to</li></ul><p>1. Analyze and restructure the logical query plan.</p><p>2. Apply optimizations like constant folding, expression pruning, and pipelining transformations.</p><p>Let’s see one more example to understand the difference between Catalyst-optimized and non-optimized functions. In this case, we’ll standardize a list of product colors from the generated dataset using both transform() (Catalyst-supported) and a Python UDF (non-Catalyst).</p><p>Non-Catalyst:</p><pre>from pyspark.sql.functions import udf, col<br>from pyspark.sql.types import ArrayType, StringType<br>import time<br><br>@udf(returnType=ArrayType(StringType()))<br>def standardize_colors(colors):<br>    return [c.upper() if c else None for c in colors]<br><br>start = time.time()<br><br>df_udf = df.withColumn(&quot;standard_colors&quot;, standardize_colors(col(&quot;color_list&quot;)))<br><br>df_udf.write.mode(&quot;overwrite&quot;).format(&quot;noop&quot;).save()<br>print(f&quot;UDF version Time: {time.time() - start:.2f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPIDrpDPDdgxev_xCrmMpg.png" /></figure><p>Catalyst Optimized:</p><pre>from pyspark.sql.functions import expr, transform, upper, col<br>import time<br> <br>df_transform = df.withColumn(<br>    &quot;standard_colors&quot;,<br>    transform(col(&quot;color_list&quot;), lambda c: upper(c))<br>)<br> <br>start = time.time()<br>df_transform.write.mode(&quot;overwrite&quot;).format(&quot;noop&quot;).save()<br>print(f&quot;Catalyst transform() Time: {time.time() - start:.2f} seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXrnTfh1oFbqDKxwN4aA6Q.png" /></figure><p>The Catalyst optimizer plays a key role in improving the performance of PySpark code. By using built-in functions and SQL-native transformations, you ensure your pipelines are scalable and efficient. Avoid Python UDFs when performance matters, and always inspect execution plans using .explain() or .queryExecution() to verify if Catalyst is being leveraged.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48dd1c75d037" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>