<?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 Joyan Bhathena on Medium]]></title>
        <description><![CDATA[Stories by Joyan Bhathena on Medium]]></description>
        <link>https://medium.com/@joyansbhathena?source=rss-8e218175ad95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9gAgb6BfnUTlw5DR8GX5yw.jpeg</url>
            <title>Stories by Joyan Bhathena on Medium</title>
            <link>https://medium.com/@joyansbhathena?source=rss-8e218175ad95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:04:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joyansbhathena/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[User-defined Functions in BigQuery — GA4 Use Cases]]></title>
            <link>https://joyansbhathena.medium.com/user-defined-functions-in-bigquery-ga4-use-cases-416cb02bcbd8?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/416cb02bcbd8</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[digital-analytics]]></category>
            <category><![CDATA[ga4]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Fri, 08 May 2026 13:05:31 GMT</pubDate>
            <atom:updated>2026-05-08T13:05:31.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpNqJYmDPtHzB5qzDXcCYA.png" /></figure><p>If you’ve worked with GA4 data in BigQuery, you’ve probably written the same UNNEST statement more times than you can count.</p><p>That’s just the nature of GA4’s nested schema — event parameters, user properties, items — they’re all stored as repeated records, and every query needs to unpack them before you can do anything useful.</p><p>UDFs won’t remove that complexity, but they can hide it, so you write it once and call it anywhere. This article walks through what UDFs are, when they’re worth reaching for, and most importantly how they apply specifically to GA4 data in BigQuery.</p><h3>1. What are UDFs</h3><p>UDFs provide users a way to create their own functions that they can use to reduce repetitive work. Think about it, how many times do you need to use the UNNEST event params statement to work with GA4 — wouldn’t it be easier to have a function reduce that work.</p><p>At the time of writing this, we have 3 options of creating UDFs in BigQuery [1]: SQL, JavaScript, Python. For the sake of this article, we will focus on SQL-based UDFs.</p><p>There are two types of UDFs based on the reusability</p><ol><li>Temporary UDFs only exist within the scope of the query where it’s defined</li><li>Persistent UDFs can be used across multiple queries</li></ol><h3>2. When to use UDFs</h3><p>So when should you consider using an UDF, here are some scenarios [2]:</p><ol><li>When you have a lengthy statement that’s used frequently</li><li>When the basic functions are not enough — for advanced use cases like looping through data</li></ol><h3>3. How to create UDFs in BigQuery</h3><p>The syntax for BigQuery SQL User-Defined Functions (UDFs) depends on whether you want the function to be temporary (available only in the current session) or persistent (stored in a dataset for future use).</p><h4>1. Temporary SQL UDF Syntax</h4><p>Temporary functions are defined at the start of a query and exist only for the duration of that specific multi-statement query or session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjhRwDr106jSWWinGHW92w.png" /></figure><h4>2. Persistent SQL UDF Syntax</h4><p>Persistent functions are stored in a BigQuery dataset. They can be called from any query as long as the user has the appropriate permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5ke-EE92Z9UQu4eIqAklg.png" /></figure><h3>4. GA4 UDFs</h3><p>Before diving in, a quick recap on why GA4 queries tend to get verbose [3].</p><p>When GA4 exports data to BigQuery, event parameters and user properties aren’t stored as flat columns — they’re stored as arrays of key-value STRUCT pairs. So to get something as simple as the page_location value, you have to UNNEST the event_params array and filter by key. Every single time. That’s exactly the kind of repetitive pattern UDFs are built for.</p><p>Here are three UDFs that will cover the majority of what you’ll run into day-to-day.</p><h4>UDF 1 — Extract Any Event Parameter</h4><p>This is the one you’ll use most. The pattern of unnesting event_params, filtering by key, and then coalescing across string_value, int_value, and float_value comes up in almost every GA4 query.</p><pre>CREATE OR REPLACE FUNCTION `your_project.your_dataset.get_event_param`(<br>event_params ARRAY&lt;STRUCT&lt;<br>key STRING,<br>value STRUCT&lt;<br>string_value STRING,<br>int_value INT64,<br>float_value FLOAT64,<br>double_value FLOAT64<br>&gt;<br>&gt;&gt;,<br>param_key STRING<br>)<br>RETURNS STRING AS ((<br>SELECT<br>COALESCE(<br>ep.value.string_value,<br>CAST(ep.value.int_value AS STRING),<br>CAST(ep.value.float_value AS STRING),<br>CAST(ep.value.double_value AS STRING)<br>)<br>FROM UNNEST(event_params) AS ep<br>WHERE ep.key = param_key<br>LIMIT 1<br>));</pre><p><strong>Usage</strong></p><p>Instead of writing the full UNNEST block every time:</p><pre>-- Without UDF<br>SELECT<br>event_name,<br>(SELECT ep.value.string_value FROM UNNEST(event_params) ep WHERE ep.key = &#39;page_location&#39; LIMIT 1) AS page_location,<br>(SELECT ep.value.string_value FROM UNNEST(event_params) ep WHERE ep.key = &#39;page_referrer&#39; LIMIT 1) AS page_referrer<br>FROM `your_project.analytics_XXXXXXXXX.events_*`<br> <br>-- With UDF<br>SELECT<br>event_name,<br>`your_project.your_dataset.get_event_param`(event_params, &#39;page_location&#39;) AS page_location,<br>`your_project.your_dataset.get_event_param`(event_params, &#39;page_referrer&#39;) AS page_referrer<br>FROM `your_project.analytics_XXXXXXXXX.events_*`</pre><p>The savings here compound fast — once you’re pulling 5 or 6 event params in a single query, the readability difference is significant.</p><h4>UDF 2 — Extract Session ID</h4><p>ga_session_id is one of the most queried event parameters, and it’s also a slightly special case because it’s always stored as an int_value, not a string. Wrapping it in its own UDF keeps things clean and avoids the CAST showing up everywhere.</p><pre>CREATE OR REPLACE FUNCTION `your_project.your_dataset.get_session_id`(<br>event_params ARRAY&lt;STRUCT&lt;<br>key STRING,<br>value STRUCT&lt;<br>string_value STRING,<br>int_value INT64,<br>float_value FLOAT64,<br>double_value FLOAT64<br>&gt;<br>&gt;&gt;<br>)<br>RETURNS INT64 AS ((<br>SELECT ep.value.int_value<br>FROM UNNEST(event_params) AS ep<br>WHERE ep.key = &#39;ga_session_id&#39;<br>LIMIT 1<br>));</pre><p><strong>Usage</strong></p><p>A common pattern in GA4 BigQuery work is constructing a unique session key by combining user_pseudo_id and ga_session_id. With the UDF it’s a lot less noisy:</p><pre>SELECT<br>user_pseudo_id,<br>`your_project.your_dataset.get_session_id`(event_params) AS session_id,<br>CONCAT(<br>user_pseudo_id,<br>&#39;_&#39;,<br>CAST(`your_project.your_dataset.get_session_id`(event_params) AS STRING)<br>) AS unique_session_key<br>FROM `your_project.analytics_XXXXXXXXX.events_*`</pre><h4>UDF 3 — Strip Query Parameters from a URL</h4><p>GA4 captures page_location as the full URL — query string and all. For most analyses (page-level traffic, funnel steps, content grouping), you want the clean path without ?utm_source=… or ?ref=… tagging along. This UDF handles it using BigQuery’s native REGEXP_EXTRACT.</p><pre>CREATE OR REPLACE FUNCTION `your_project.your_dataset.clean_page_path`(<br>page_location STRING<br>)<br>RETURNS STRING AS (<br>REGEXP_EXTRACT(page_location, r&#39;^(?:https?://[^/]+)?(/[^?#]*)&#39;)<br>);</pre><p><strong>Usage</strong></p><pre>SELECT<br>`your_project.your_dataset.get_event_param`(event_params, &#39;page_location&#39;) AS full_url,<br>`your_project.your_dataset.clean_page_path`(<br>`your_project.your_dataset.get_event_param`(event_params, &#39;page_location&#39;)<br>) AS clean_path<br>FROM `your_project.analytics_XXXXXXXXX.events_*`<br>WHERE event_name = &#39;page_view&#39;</pre><p>This also composes nicely with get_event_param — which is the real benefit of persistent UDFs. Once your team has a few of these defined in a shared dataset, queries start to look less like BigQuery boilerplate and more like actual business logic.</p><h4>When to make these persistent vs. temporary</h4><p>For one-off exploratory queries, the temporary version is fine. But the real payoff of these GA4 UDFs comes when you make them persistent and store them in a shared dataset that your whole team can access. That way:</p><ul><li>Analysts aren’t each writing their own version of the UNNEST pattern</li><li>If the logic ever needs updating (e.g., handling a new parameter type), you fix it in one place</li></ul><p>The get_event_param UDF in particular is worth making persistent immediately — it’s universal enough that virtually every GA4 query benefits from it.</p><h3>Closing</h3><p>UDFs are a great way to avoid repetitive code, especially when working with GA4 data in BigQuery. Investing an hour to set up a shared UDF library will pay off pretty quickly. Start with get_event_param — that alone will save you from rewriting the UNNEST block in every query you write.</p><h3>References</h3><ul><li>[1] Google Cloud Documentation — <a href="https://cloud.google.com/bigquery/docs/user-defined-functions">BigQuery User-Defined Functions</a></li><li>[2] Alex Ignatenko — <a href="https://www.alexignatenko.com/post/how-can-udf-simplify-complex-queries-in-bigquery">How can UDFs simplify complex queries in BigQuery?</a></li><li>[3] Google Analytics Help — <a href="https://support.google.com/analytics/answer/7029846">BigQuery Export Schema for GA4</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=416cb02bcbd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I’m Automating My Job Search and of course with AI]]></title>
            <link>https://joyansbhathena.medium.com/how-im-automating-my-job-search-and-of-course-with-ai-f0ca334eddd6?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ca334eddd6</guid>
            <category><![CDATA[ai-automation]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[job-search]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 17:48:02 GMT</pubDate>
            <atom:updated>2026-04-01T17:48:02.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I’m Automating My Job Search</h3><p><strong><em>Tech Stack:</em></strong><em> Python, Github Actions, Groq API</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyjWLR4zXe2JHfhBbd1z-A.png" /></figure><p>I have been actively searching for a job for about 2 months now and was looking for parts that I felt could be automated. For me, it’s the search that’s the most daunting task of all. Because the thing is — while you’re searching for jobs across multiple job boards and company portals, you feel like you’re doing something productive. But that’s far from the truth. Your time could be better invested in upskilling, networking, drafting cover letters, or just taking a break.</p><p>So that’s the part I wanted to automate the most.</p><h3>Sourcing</h3><p>Initially I tried web scraping, but that approach wasn’t feasible. Different job boards have different layouts — which can change at any time. A scraper that works today might break tomorrow with a UI update, and you’d have no idea until you check why your sheet has been empty for three days.</p><p>So I opted for third-party APIs instead. There are several out there that aggregate results from LinkedIn, Indeed, Glassdoor, and more under one endpoint. No scraping, no fragile HTML parsing — just a clean API response.</p><p>The one I went with is <strong>JSearch on RapidAPI</strong>. It pulls from multiple job boards simultaneously and the free tier gives you 200 requests per month.</p><p>The tricky part is the quota. 200 requests per month sounds like a lot until you realise each search query = 1 request. I run 4–5 queries per day, 5 days a week — which works out to roughly 100 requests/month. That leaves a comfortable buffer for reruns and debugging.</p><p>One thing that caught me off guard: the API has a country parameter that defaults to us regardless of what you put in the query string. I was getting 0 results before I figured that out. Always check the raw API response before touching your code.</p><h3>Deduplication</h3><p>Since the pipeline runs every weekday, the same job will appear in results across multiple runs. Re-scoring the same listing is a waste of both API quota and LLM tokens.</p><p>The solution is a simple seen_ids.json file that stores every job ID that&#39;s ever been processed. Before scoring, new results are filtered against this list. After each run, the file is updated and committed back to the repository automatically by the GitHub Actions workflow.</p><p>No database needed. The repo itself is the state store.</p><p>There’s also a secondary dedup layer — same job title + company combination — to catch employers who post the same role multiple times with different job IDs.</p><h3>Scoring the Jobs</h3><p>Fetching is the easy part. The real challenge is deciding which jobs are worth your time.</p><p>If I’m fetching 40 jobs per day and checking each one manually, I’ve just moved the problem — not solved it. So I pass every new job through an LLM scorer before it reaches my sheet.</p><p>I’m using <strong>Groq’s API</strong> with llama-4-scout (30K tokens per minute on the free tier — important for throughput). The scorer takes the job title, company, location, and the requirements section of the JD and returns a structured JSON with a score and reasoning across four dimensions:</p><ul><li><strong>Title match</strong> — is this actually a data analyst or analytics engineering role?</li><li><strong>Tools match</strong> — does the JD mention tools I know (SQL, Python, GA4, BigQuery)?</li><li><strong>Seniority fit</strong> — do I realistically qualify?</li><li><strong>German language requirement</strong> — I’m B1, which rules out a lot of German-only roles</li></ul><p>The score goes from 0 to 10. Jobs above the threshold land in the main “Jobs” tab. Everything else goes to a “Rejected” tab so I can audit the scorer’s calibration over time.</p><p><strong>A couple of learnings from this step:</strong></p><p>The LLM scores more consistently when asked to justify each component before outputting a number. If you just ask “rate this job 0–10”, you get arbitrary numbers with no reasoning. When you ask it to evaluate title fit, tools, seniority, and German requirements separately first — the final score actually reflects something.</p><p>The LLM also makes arithmetic mistakes. I initially asked it to compute the final score itself (base score minus German language penalty). It would output the wrong number roughly 30% of the time, sometimes writing the correct calculation in the summary text but returning the wrong value in the score field. The fix was to separate concerns: the LLM returns only the base score and the penalty as separate fields, and Python does final_score = base_score - german_penalty. Two lines. No more calculation errors.</p><p>Finally, the LLM performed better when given a persona and overall task context in a system-level prompt, and only the candidate profile + job requirements in the user message. Mixing everything into one prompt produced less structured output.</p><h3>Extracting Requiremets from Job Description</h3><p>One issue I ran into: job descriptions are long, and the requirements section — the part that actually tells you what they’re looking for — is rarely at the top.</p><p>Sending the first 2000 characters to the LLM means it’s mostly reading the company intro and role overview, not the actual requirements. The scorer was making decisions with the wrong information.</p><p>The fix was to scan the full JD for known requirements headers before sending anything to the LLM. Things like:</p><ul><li>English: <em>Requirements, Your Profile, What you bring, The ideal candidate</em></li><li>German: <em>Dein Profil, Ihr Profil, Was Sie mitbringen sollten, Anforderungen</em></li></ul><p>If a header is found, the pipeline extracts from that point to the next end-section header (benefits, “What we offer”, etc.) and sends that to the LLM instead. If no header is found, it falls back to the last third of the JD — requirements almost always appear near the end.</p><p>The match rate on the first run was about 83%. For the unmatched JDs, the full text is logged to a file so I can review them manually and add the missing header patterns over time.</p><h3>Infrastructure</h3><p>The pipeline runs on <strong>GitHub Actions</strong> on a cron schedule — 06:30 CET on weekdays. No server, no cloud function, no cost. The workflow injects API keys from GitHub Secrets, runs the pipeline, and commits the updated seen_ids.json back to the repo.</p><p>The whole thing is zero infrastructure to maintain. If something breaks overnight, I see it in the Actions log in the morning.</p><h3>End Results</h3><p>The initial results have been positive. I’m surfacing jobs from platforms I’d never visited, and the scoring means I spend maybe 5 minutes reviewing my sheet each morning instead of an hour across 4 job boards. The rejected tab is also useful — it gives me a quick sense of which query terms are pulling in irrelevant results.</p><p>There’s still room to improve. The German language assessment isn’t perfect — it’s based on signals in the JD text rather than ground truth. The query set needs tuning as I learn which search terms actually return relevant results on the German market. And I want to add a weekly summary that tells me things like average score trend and which companies are hiring most actively.</p><p>But it works. And it runs itself.</p><p>The full code is on GitHub: <a href="https://github.com/Joyan9/Job-Search-Automation">Job-Search-Automation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ca334eddd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Market Basket Analysis: Support, Confidence, and Lift]]></title>
            <link>https://joyansbhathena.medium.com/understanding-market-basket-analysis-support-confidence-and-lift-037e91f65585?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/037e91f65585</guid>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[product-bundling]]></category>
            <category><![CDATA[advanced-sql]]></category>
            <category><![CDATA[market-basket-analysis]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 12:41:09 GMT</pubDate>
            <atom:updated>2025-12-26T12:41:09.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxEAFHelToqZ-EeWs-IKzg.png" /></figure><p>So I came across<a href="https://www.startdataengineering.com/post/how-to-get-better-at-advanced-sql/"> this article/tutorial</a> from<a href="https://www.linkedin.com/in/josephmachado1991?miniProfileUrn=urn%3Ali%3Afs_miniProfile%3AACoAAA684x4B5pdMD2HvUDXj-mOYN0I94qwhK4I"> Joseph M.</a> — if you don’t know him, he’s a data engineering content creator worth following — his piece titled “How to Get Really Good at Advanced SQL for Data Engineering” showed me how I could get better at SQL to actually deliver business value (which is the very purpose any tech was created for in the first place).</p><p>He defines Advanced SQL as “solving complex requirements with easy-to-understand code” — and honestly, that resonated with me.</p><p>When I started my first job 3 years back, the very first challenge I encountered was unclear requirements from stakeholders. This was me who had just cleared 4 years of engineering where everything was defined for me — the exam syllabus, the timetable, the important topics etc. So it was quite humbling to actually try to understand what the other person wants. They don’t just want plain numbers, they want numbers with business logic.</p><p>Joseph’s article was a perfect example of how requirements are converted into SQL code. One particular example stood out to me the most — market basket analysis. This is a type of analysis done to understand which products are often bought together. In particular, it was the defining of these three metrics with respect to the analysis that caught my eye:</p><ul><li>Support</li><li>Confidence</li><li>Lift</li></ul><p>Now if you’ve had some experience with A/B testing, you would know that these are exactly the metrics we look at for evaluating variants — but I did not consider how these could be used for regular analysis as well (i.e. no actual test conducted).</p><p>So in this piece I’ll elaborate on these metrics and their significance.</p><h3>#1 Support: Tells me — How Popular Is This Pairing?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yV_qPjdWe66W3LUr6zyAJw.png" /></figure><p>Support signifies the popularity or frequency of a product combination.</p><p><strong>Formula:</strong> P(A AND B) = (orders with both products) / (total orders)</p><p><strong>What it measures:</strong> How popular a product grouping is</p><p><strong>Business meaning:</strong> How often do these two products appear together across all transactions? A high support value means this product combination occurs frequently in your data.</p><p><strong>Example:</strong> If 100 out of 1,000 orders contain both Product A and Product B, the support is 10%. This tells you this is a relatively common pairing.</p><h3>#2 Confidence: If they buy A, what are the Chances they buy B?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJ2LPjp4d_aYU0syzjGWfg.png" /></figure><p>This is essentially conditional probability — if we know that event B has occurred, what’s the probability of event A? This is one of my favorite topics in probability theory, and I actually wrote a piece on it long back (<a href="https://medium.com/@joyansbhathena/the-bayes-theorem-football-fc4d4f3c8a1a">linking it here for reference</a>).</p><p><strong>Formula:</strong> P(B|A) = (orders with both A and B) / (orders with A)</p><p><strong>What it measures:</strong> The likelihood of certain products being bought together</p><p><strong>Business meaning:</strong> If someone buys Product A, what’s the probability they’ll also buy Product B? This is directional — confidence(A→B) ≠ confidence(B→A).</p><p><strong>Example:</strong> If 100 orders contain Product A, and 30 of those also contain Product B, the confidence is 30%. This means 30% of customers who buy A also buy B.</p><h3>#3 Lift: The Part That Gets Interesting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tacRvGfGLt6mdWqqb6m3Vg.png" /></figure><p>Lift measures association strength — this is where things get interesting, and to me personally it was slightly non-intuitive to understand. It’s a measure of how much the products are truly associated beyond what you’d see by pure coincidence.</p><p><strong>Formula:</strong> Lift = P(A AND B) / (P(A) × P(B))</p><p><strong>What it measures:</strong> Whether or not combining two products inside the product suite will improve the chances of making a sale.</p><p><em>Lift compares what actually happens (real probability of buying A and B together) vs. what would happen if products were completely independent (expected probability if no relationship exists).</em></p><p><strong>Business meaning:</strong> Does buying Product A actually increase the likelihood of buying Product B, or would B be purchased at the same rate anyway?</p><p>Here’s how to interpret lift values:</p><ul><li>Lift &gt; 1: Positive correlation (buying A increases the chance of buying B)</li><li>Lift = 1: No correlation (A and B are independent)</li><li>Lift &lt; 1: Negative correlation (buying A decreases the chance of buying B)</li></ul><p><strong>Example:</strong> If lift = 2.5, customers who buy A are 2.5 times more likely to buy B than random customers, making this a strong candidate for product bundling or cross-selling.</p><h3>Final Words</h3><p>In summary each metric addresses a different business question</p><ul><li>Support → Is this pairing common enough to act on?</li><li>Confidence → How reliable is this association for recommendations?</li><li>Lift → Is this a genuine relationship or just coincidence?</li></ul><p>And we need all three because a high confidence doesn’t mean much if support is very low (rare event), and high support alone doesn’t tell you if the relationship is meaningful (that’s where lift comes in).</p><p>I hope this piece has given you a clearer picture of support, confidence, and lift — and how these metrics can actually help you understand customer behavior beyond just the numbers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=037e91f65585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Indian Government Open Datasets for Projects]]></title>
            <link>https://joyansbhathena.medium.com/top-10-indian-government-open-datasets-for-projects-43f829e485cd?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f829e485cd</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[government-data]]></category>
            <category><![CDATA[open-data]]></category>
            <category><![CDATA[data-project]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 19:52:06 GMT</pubDate>
            <atom:updated>2025-10-22T19:52:06.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oXxg3LCg3ffWv0C4Pd4yWw.png" /><figcaption><a href="https://www.data.gov.in/">https://www.data.gov.in/</a></figcaption></figure><p>I stumbled across my country’s (India) open data portal and, safe to say, I was positively surprised by the number of datasets available. Moreover, many of the datasets can be accessed via APIs, and they also mention how frequently the data is updated.</p><p>The goal of writing this article is to achieve two things</p><ol><li>Create awareness of the available datasets so that people start using them and also provide feedback to the Open Data Portal for improvements</li><li>To hold stakeholders accountable. As citizens of a country, it is our right and duty to ask questions, and what better than data to back your analysis, right?</li></ol><p>So in this article, I will list 10 datasets that I found to be of value and could lead to some really amazing data projects.</p><h3>#1 Real time Air Quality Index</h3><p><strong>Granularity:</strong> Hourly</p><p><strong>Government Organisation:</strong> Central Pollution Control Board (CPCB)</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/real-time-air-quality-index-various-locations">https://www.data.gov.in/resource/real-time-air-quality-index-various-locations</a></p><p>Insert code how to access dataset</p><h3>#2 State-wise Voters Information during 2024</h3><p><strong>Granularity:</strong> Five Yearly</p><p><strong>Government Organisation:</strong> Election Commission India (ECI)</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/state-wise-voters-information-during-2024#api">https://www.data.gov.in/resource/state-wise-voters-information-during-2024</a></p><h3>#3 District-wise Demographic Data of Unorganised Workers registered on eShram</h3><p><strong>Granularity:</strong> Daily</p><p><strong>Government Organisation:</strong> Election Commission India (ECI)</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/state-wise-voters-information-during-2024#api">https://www.data.gov.in/resource/state-wise-voters-information-during-2024</a></p><h3>#4 Current Daily Price of Various Commodities from Various Markets (Mandi)</h3><p><strong>Granularity:</strong> Daily</p><p><strong>Government Organisation:</strong> -</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/current-daily-price-various-commodities-various-markets-mandi">https://www.data.gov.in/resource/current-daily-price-various-commodities-various-markets-mandi</a></p><h3>#5 Physical &amp; Financial Progress of Pradhan Mantri Gram Sadak Yojna (PMGSY)</h3><p><strong>Granularity:</strong> Daily</p><p><strong>Government Organisation:</strong> Pradhan Mantri Gram Sadak Yojna (PMGSY)</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/physical-financial-progress-pradhan-mantri-gram-sadak-yojna-pmgsy-date">https://www.data.gov.in/resource/physical-financial-progress-pradhan-mantri-gram-sadak-yojna-pmgsy-date</a></p><h3>#6 Aadhaar Monthly Enrolment data</h3><p><strong>Granularity:</strong> Monthly</p><p><strong>Government Organisation:</strong> -</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/aadhaar-monthly-enrolment-data">https://www.data.gov.in/resource/aadhaar-monthly-enrolment-data</a></p><h3>#7 Monthly Indigenous Crude Oil Production</h3><p><strong>Granularity:</strong> Monthly</p><p><strong>Government Organisation:</strong> Petroleum Planning &amp; Analysis Cell (PPAC)</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/monthly-indigenous-crude-oil-production#api">https://www.data.gov.in/resource/monthly-indigenous-crude-oil-production</a></p><h3>#8 Kisan Call Centre (KCC) — Transcripts of farmers queries &amp; answers</h3><p><strong>Granularity:</strong> Daily</p><p><strong>Government Organisation:</strong> Kisan Call Center Data (Queries of Farmers)</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/kisan-call-centre-kcc-transcripts-farmers-queries-answers">https://www.data.gov.in/resource/kisan-call-centre-kcc-transcripts-farmers-queries-answers</a></p><h3>#9 Aviation Grievance</h3><p><strong>Granularity:</strong> Daily</p><p><strong>Government Organisation:</strong> Air Sewa</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/aviation-grievance-date">https://www.data.gov.in/resource/physical-financial-progress-pradhan-mantri-gram-sadak-yojna-pmgsy-date</a></p><h3>#10 Wholesale Price Index</h3><p><strong>Granularity:</strong> Monthly</p><p><strong>Government Organisation:</strong> Ministry of Commerce and Industry</p><p><strong>Link to Dataset: </strong><a href="https://www.data.gov.in/resource/wholesale-price-index-base-year-2011-12-till-last-month">https://www.data.gov.in/resource/wholesale-price-index-base-year-2011-12-till-last-month</a></p><h3>How to Access Data from The Open Data Portal</h3><ol><li>Select the dataset that you want to work with; each of them requires a separate API key. For this example, I’ll use the <a href="https://www.data.gov.in/resource/monthly-indigenous-crude-oil-production#api">Monthly Indigenous Crude Oil Production</a> dataset.</li><li>Navigate to the dataset page in the Open Data Portal and click on the API section.</li><li>Here you will have an option to “Generate API Key”.</li><li>Once you have the API Key, you are free to use whichever programming language you see fit to start ingesting the data. I’ll go with Python, and the code snippet below shows how to load the dataset.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e723ada262d7bb29a94f0957fcc9492b/href">https://medium.com/media/e723ada262d7bb29a94f0957fcc9492b/href</a></iframe><h3>Conclusion</h3><p>India’s Open Data Portal offers a treasure trove of information that can empower citizens, researchers, and developers to create meaningful data-driven projects. From tracking air quality and agricultural prices to analyzing voter demographics and infrastructure development, these datasets provide invaluable insights into various aspects of Indian society and governance. By leveraging these resources, we can not only build innovative applications but also promote transparency and accountability in government operations. I encourage you to explore these datasets, experiment with them in your projects, and contribute feedback to help improve the Open Data Portal for the entire community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f829e485cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partitioning in BigQuery with dlt]]></title>
            <link>https://joyansbhathena.medium.com/partitioning-in-bigquery-with-dlt-2d3ad7d1b843?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3ad7d1b843</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 16:49:52 GMT</pubDate>
            <atom:updated>2025-07-18T16:49:52.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJzf5_b8Ehhao-w1qZRHBQ.png" /></figure><p>In this article, we will cover how to load data to <strong>BigQuery </strong>and partition it using <strong>dlt</strong>, a Python-based data ingestion and loading library.</p><h3>TL;DR</h3><blockquote><em>Learn how to use dlt (a Python data ingestion library) to load data into BigQuery with partitioning enabled.</em></blockquote><blockquote><em>We’ll walk through building a pipeline that fetches weather data from OpenMeteo’s API and loads it into a partitioned BigQuery table.</em></blockquote><blockquote><em>Key steps include setting up BigQuery credentials, using the</em> bigquery_adapter()<em> to specify partitioning columns, and understanding the trade-offs of partitioning in BigQuery.</em></blockquote><p>First, a quick refresher on the <strong>prerequisites</strong></p><blockquote>dlt is an open-source Python library that loads data from various, often messy data sources into well-structured, live datasets.</blockquote><p><strong>Main features of dlt</strong></p><ul><li>Automatically infers schemas and can unnest nested data structures</li><li>A lot of ready-to-use sources and destinations are available, making the work much easier</li><li>Can be deployed where Python can run, so basically almost everywhere</li><li>Makes handling schema evolution, incremental loading, and implementing slowly changing dimensions extremely straightforward</li></ul><p><em>Read more about dlt </em><a href="https://dlthub.com/docs/intro"><em>here</em></a><em>.</em></p><p>Next up,<strong> Partitioning — </strong>It is the practice of storing data in separate partitions instead of a single huge block. Partitioned tables help in reducing query costs and also improve query performance. You partition tables by specifying a partition column which is used to segment the table.</p><h3>Partitioning in BigQuery</h3><h4>Pros of Partitioning</h4><ol><li>You can <strong>reduce query costs</strong> drastically if you partition the table appropriately. This is because BQ charges you based on the bytes read. You can test this by using BigQuery’s public datasets as shown in the images below</li><li>With partitioned tables, you <strong>unlock other features like automatically deleting older partitions or archiving them to save on storage costs</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4WsdR_CqfQWV-bDDt97Ew.png" /><figcaption>Query Cost Without Using Partitioned Column as Filter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpWnbzAKeY3iQ1EfGWtMnw.png" /><figcaption>Query Cost With Using Partitioned Column as Filter</figcaption></figure><p>You can try running the query yourself to see the difference.</p><pre>SELECT term <br>FROM `bigquery-public-data.google_trends.international_top_rising_terms` <br>WHERE refresh_date = “2025–07–13” AND country_name = “India”<br>LIMIT 10</pre><h4>Cons of Partitioning</h4><ol><li>In BigQuery, you <strong>can only partition based on a single column</strong>, and you can only partition a table while creating it.</li><li>There are certain platform-specific restrictions for choosing the partition column as well.</li></ol><p>Nevertheless, as it is with every engineering decision, partitioning is also a game of trade-offs. It comes down to each specific use case whether it’s worth partitioning or not. But generally, I’d say we should partition fact tables as they tend to be longer.</p><h3>dlt-BigQuery Pipeline with Partitioning</h3><p>To get started, let us first install dlt. Here we install the BigQuery and DuckDB adapters; the latter will be used for development.</p><pre>pip install “dlt[bigquery]” “dlt[duckdb]”</pre><p>For this tutorial, we will be using the <a href="https://open-meteo.com/en/docs/dwd-api">OpenMeteo’s Weather API</a> to fetch Berlin’s weather forecast. Let’s first get a look at the data and the API</p><pre>import requests<br>import pandas as pd<br><br># Coordinates for Berlin<br>latitude = 52.52<br>longitude = 13.41<br><br># Define API endpoint and parameters<br>url = &#39;https://api.open-meteo.com/v1/forecast&#39;<br><br>params = {<br>         “latitude”: latitude,<br>         “longitude”: longitude,<br>         “hourly”: [“temperature_2m”, “precipitation”, “apparent_temperature”, “relative_humidity_2m”],<br>         “models”: “icon_seamless”<br>        }<br><br># Make the request<br>response = requests.get(url, params=params)<br>data = response.json()<br><br># Convert to pandas DataFrame<br>df = pd.DataFrame(data[“hourly”])<br>print(df.head())</pre><p>There are several other weather fields you can add, but for now we can keep it simple. The above code prints out a dataframe with columns `time`, `temperature_2m`, `precipitation`, `apparent_temperature`, and `relative_humidity_2m`.</p><p>Now, let’s convert this code into a dlt pipeline. To create a dlt pipeline, you basically need two main things:</p><ul><li>A data source function that yields each record or a bunch of records</li><li>A destination to ingest the records. For development, we will use DuckDB</li></ul><p>Below we have a simple dlt pipeline that loads hourly weather forecasts for the current day. The code essentially comprises two functions: one is the dlt resource which is responsible for generating data, and the main function initializes dlt’s pipeline object to load data to the destination.</p><pre>import requests<br>import dlt<br><br># Define API endpoint and parameters<br>url = “https://api.open-meteo.com/v1/forecast<br><br># define a dlt resource that yields data<br>@dlt.resource(name=”hourly_weather”, <br>              primary_key=”time”, <br>              write_disposition=”merge”)<br>def get_hourly_weather(latitude, longitude):<br>    params = {<br>            “latitude”: latitude,<br>            “longitude”: longitude,<br>            “hourly”: [“temperature_2m”, “precipitation”, “apparent_temperature”, “relative_humidity_2m”],<br>            “models”: “icon_seamless”,<br>            “forecast_days”: 1<br>            }<br><br>    # Make the request<br>    response = requests.get(url, params=params)<br>    hourly_data = response.json()<br>    <br>    # Extract the hourly data and metadata<br>    hourly_variables = hourly_data[“hourly”]<br>    hourly_units = hourly_data[“hourly_units”]<br>    timestamps = hourly_variables[“time”]<br>    for i in range(len(timestamps)):<br>      record = {“time”: timestamps[i]}<br>      # Add all weather variables with units in column name<br>      for key in hourly_variables:<br>        if key != “time”: # Skip time as we already added it<br>          key_name = f”{key}_{hourly_units[key].strip()}”<br>          record[key_name] = hourly_variables[key][i]<br>      <br>      yield record<br><br>def main():<br>   # Create and configure the pipeline object<br>   pipeline = dlt.pipeline(<br>                           pipeline_name=”berlin_weather_data”,<br>                           destination=”duckdb”, # for testing let&#39;s use duckdb<br>                           dataset_name=”open_meteo_weather”<br>                           )<br><br>  # Coordinates for Berlin<br>  latitude = 52.52<br>  longitude = 13.41<br>   <br>  pipeline.run(get_hourly_weather(latitude, longitude))<br><br>  print(pipeline.last_trace)<br>  print(pipeline.dataset().hourly_weather.df())<br><br>if __name__ == “__main__”:<br>    main()</pre><p>Now that we have our pipeline code ready, we can move on to modifying the destination to BigQuery and setting the partitioning column.</p><p>First, we need to set up a service account in BigQuery. Follow the steps below:</p><p>1. Log in to or create a <a href="https://console.cloud.google.com/">Google Cloud account</a></p><p>2. Create a new Google Cloud project</p><p>3. Create a service account and grant BigQuery permissions<br> — You will then need to create a <a href="https://console.cloud.google.com/">service account</a>.<br> — After clicking the “Go to Create service account” button on the linked docs page, select the project you created and name the service account whatever you would like.</p><p>4. Click the Continue button and grant the following roles, so that dlt can create schemas and load data:</p><pre>BigQuery Data Editor<br>BigQuery Job User<br>BigQuery Read Session User</pre><p>5. Download the service account JSON<br> — In the service accounts table page that you’re redirected to after clicking “Done” as instructed above, select the three dots under the Actions column for the service account you created and select “Manage keys.”<br> — Click the “Add key” button, then the “Create new key” button, and finally the “Create” button, keeping the preselected JSON option.<br> — A JSON file that includes your service account private key will then be downloaded.</p><p>6. Add the Service Account Credentials to dlt<br> — In your project root directory, create a folder with the name `.dlt` within which you will create a `secrets.toml` file<br> — Set up the `secrets.toml` file in the following way:</p><pre>[destination.bigquery]<br>location = “EU” # YOU CAN CHANGE THIS TO THE DESIRED LOCATION<br><br>[destination.bigquery.credentials]<br>project_id = “REPLACE WITH PROJECT ID” <br>private_key = “ — — -BEGIN PRIVATE KEY — — -\nREPLACE THIS WITH YOUR PRIVATE KEY==\n — — -END PRIVATE KEY — — -\n” <br>client_email = “REPLACE WITH CLIENT EMAIL”</pre><p>Alright, now we are ready to make changes to our pipeline. We will use the BigQuery adapter to assign column-level hints for partitioning. You can use the same column-level hints to set the clustering columns as well, but that’s a different topic.</p><p><strong>What are we going to change in our existing code?</strong></p><ul><li>Import some additional modules</li></ul><pre>from dlt.destinations.adapters import bigquery_adapter<br>from datetime import date</pre><ul><li>Specify the data type for the partitioning column in the resource decorator</li></ul><pre><br># define a dlt resource that yields data<br>@dlt.resource(name=”hourly_weather”, <br>             primary_key=”time”, <br>             write_disposition=”merge”,<br>             # set the partitioning column data type<br>             columns=[<br>             {“name”: “date”, “data_type”: “date”}<br>             ])<br>def get_hourly_weather(latitude, longitude):<br> </pre><ul><li>Change destination to BigQuery</li></ul><pre>pipeline = dlt.pipeline(<br>                         pipeline_name=”berlin_weather_data”,<br>                         destination=”bigquery”, <br>                         dataset_name=”open_meteo_weather”<br>                        )</pre><ul><li>Use the BigQuery adapter that we imported earlier to specify the partitioning column</li></ul><pre>get_hourly_weather_partitioned = bigquery_adapter(get_hourly_weather, <br>                                                  partition=”date”)<br><br>pipeline.run(get_hourly_weather_partitioned(latitude, longitude))</pre><p>The BigQuery adapter returns a dlt resource, and that is what we use to run the pipeline.</p><p><strong>Just like before, run the pipeline and boom — there you have it, data loaded to BigQuery and partitioned!</strong></p><h3>Complete pipeline code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8106e9c8b321a16d15dffffbbe70e580/href">https://medium.com/media/8106e9c8b321a16d15dffffbbe70e580/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3ad7d1b843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Learned While Creating a Data Pipeline that Processed 9 Million Records]]></title>
            <link>https://blog.devgenius.io/what-i-learned-while-creating-a-data-pipeline-that-processed-9-million-records-41c19dc76d3d?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/41c19dc76d3d</guid>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[open-data]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[portfolio]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 12:14:18 GMT</pubDate>
            <atom:updated>2025-09-25T12:00:19.438Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of my master’s curriculum I had a course in which we were required to create either a batch processing pipeline or a streaming pipeline. The assignment also had a few other requirements such as following a microservices architecture using docker containers, processing at least 1 million data points and clear documentation at each phase of the project.</p><p>I decided to go for batch processing and as for the dataset I found an amazing dataset on Indian Government’s Open Data Portal: <strong>“Kisan Call Centre (KCC) — Transcripts of farmers queries &amp; answers”</strong>. The data contains queries asked by farmers in Kisan Call Centre (<em>Kisan means Farmer</em>). This was an interesting dataset to me because this was the first time I was working with my country’s open data portal and secondly the data itself could be valuable to companies operating in the agriculture sector.</p><p><strong>If you would like to have a look at the project here’s the link to GitHub repository:</strong> <a href="https://github.com/Joyan9/kcc-farmer-queries-pipeline">https://github.com/Joyan9/kcc-farmer-queries-pipeline</a></p><h3>Challenges Faced and What I Did to Solve Them</h3><h4>Challenge #1: Storing Raw Data Files as JSON Leads to Difficulty in Processing</h4><p>According to the initial plan, I planned to store the raw data files and the reasoning behind this was that I directly get the output from the API in JSON format therefore there would be no processing overhead for converting to any other format.</p><p>However, when I tried to read the files using Spark it required complicated unnesting, which by the way was possible but I also faced another issue of traversing through paginated responses (covered next).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXbTV3PhCWyN832WYlJajg.png" /><figcaption><strong>Architecture Diagram V1</strong></figcaption></figure><h4>Challenge #2: API Performance Limitations</h4><p>By default the API returned 10 rows per call and provided the offset parameter to retrieve the next set of records. Ideally, it’s fairly simple code to loop over the API response pages until there are no more records to fully extract all the rows. However, repeatedly calling the API led to 504 status code (Gateway Timeout error) and even after implementing exponential backoff and retries the ingestion was not successful.</p><p>That is when I thought of using dlt (Data Load Tool) a python library built for loading data from various sources and loading data from API sources is one of its biggest forte. Why dlt made sense for my project:</p><ul><li>Built-in code for exponential backoff and retry limits</li><li>Built-in code for different types of pagination</li><li>Option to choose parquet as the write format — this solved Challenge #1, instead of saving as JSON, storing files as parquet was much easier for Spark to read</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lENA3z4C4ycJYRN_mRD2Zw.png" /><figcaption><strong>Architecture Diagram V2</strong> (Raw Data Files Stored as Parquet Files)</figcaption></figure><p><strong><em>Some Metrics from Data Ingestion Step</em></strong></p><p>The backfill run for 197 months starting from 2009 January till 2025 May took around 6 hours to complete, processing approximately 9 million records (with a maximum limit of 50,000 rows per month to avoid excessive ingestion times). This was a personal accomplishment for me as I had never run a script for so long. Moreover, I initially tried to do the ingestion without dlt and it kept failing and restarting which was painful to watch, but with dlt it did not fail even once.</p><h4>Challenge #3: Data Processing Challenges — Personally Identifiable Information (PII) Removal</h4><p>The dataset contained the responses of the Farm Tele Advisors (experts at the Kisan Call Centre who answer to the queries raised) which could contain PII such as names, email, and phone numbers. However, due to inconsistent patterns it was difficult to make sure 100% of the PII was removed.</p><p>As such there wasn’t a concrete solution that I could implement and due to the time constraint I tried to make sure that the regex pattern captures as many instances as possible.</p><pre>def mask_pii(df: DataFrame, col: str, patterns: List[Tuple[str, str]]) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    Mask PII in a column using regex patterns.<br>    &quot;&quot;&quot;<br>    for pattern, mask in patterns:<br>        df = df.withColumn(col, F.regexp_replace(F.col(col), pattern, mask))<br>    return df</pre><h4>Challenge #4: Generating Surrogate Keys for Dimensions</h4><p>The decision to model the data in STAR schema was justified due to the dimensional nature of the data but since the raw data did not have natural primary keys we had to create surrogate keys to separate out the dimensions.</p><p>Spark’s distributed nature complicated surrogate ID creation for dimensions. Performance degradation due to data shuffling to head node.</p><p>Here as well I did not have any other option to generate unique IDs for the dimensions, however we did not need to create dimensional tables every month, only for the initiation phase and then once the pipeline is setup to run every month, only a small portion of the rows would need to be scanned for new dimensional values.</p><p>There are perhaps better ways to model this data so if you have any insights on that I would love to learn about it.</p><pre>def generate_dim(df: DataFrame, col: str, id_col: str) -&gt; DataFrame:<br>    &quot;&quot;&quot;<br>    Generate a dimension table with surrogate keys.<br>    &quot;&quot;&quot;<br>    window = Window.orderBy(col)<br>    return df.select(col).distinct().withColumn(id_col, F.row_number().over(window))</pre><h4>Challenge #5: Working with Large Dataset for Visualization</h4><p>Finally it was time to visualize the processed data but every time I tried to load the complete dataset on Jupyter Notebook via DuckDB and Pandas it would crash.</p><p>I then had to use a sample of the dataset to create sample visualizations — the assignment was more focused on the data engineering aspect than the data analysis and data science part of the data therefore there wasn’t much effort put here. However, in a real-world scenario I would have used a BI tool like Power BI (was part of the conception phase but due to time constraint was replaced with Jupyter Notebook) since it can handle millions of rows.</p><p>At the end, this was the final architecture diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR8GHZigIXvzPh75kcYUqQ.png" /><figcaption><strong>Architecture Diagram V3</strong></figcaption></figure><h3>Conclusion</h3><p>This project helped me understand microservices architecture and how to actually implement it in practice. Moreover, I’ve seen firsthand that no matter how carefully you plan the execution, there are always unexpected challenges that require adaptation. That, for me, is a key lesson of engineering itself.</p><p>In terms of technical lessons, the dlt Advanced course I completed certainly helped me out and saved significant time by reducing much of the boilerplate code. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41c19dc76d3d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-i-learned-while-creating-a-data-pipeline-that-processed-9-million-records-41c19dc76d3d">What I Learned While Creating a Data Pipeline that Processed 9 Million Records</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginners Guide to Understanding Data Contracts]]></title>
            <link>https://joyansbhathena.medium.com/beginners-guide-to-understanding-data-contracts-d36221485bf0?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/d36221485bf0</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-contract]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Sat, 10 May 2025 13:57:25 GMT</pubDate>
            <atom:updated>2025-05-10T13:57:25.739Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we will cover the following topics</p><ol><li>What are Data Contracts?</li><li>Motivation Behind Creation of Data Contracts</li><li>Sample Data Contract</li></ol><h3><strong>What are Data Contracts?</strong></h3><p>When I first heard “data contract” — with no background knowledge — I could guess that it is like a contract but for data: how the data is supposed to be structured, what data types are expected, and so on. And my assumption wasn’t far fetched from the industry-accepted definition of data contracts. I’m pretty sure if you have some knowledge of data, you too would have this pre-assumed definition.</p><p>I like PayPal’s definition: “<em>A data contract defines the agreement between a data producer and consumer.”</em> [1]</p><p>The goal is simple:<strong> to ensure that downstream consumers are assured about data quality and that it’s reliable enough to build revenue-generating business applications on top of it</strong>, like ML models for pricing algorithms or real-time reports for store managers to monitor inventory.</p><p>From another perspective, data contracts can be thought as APIs but specifically for data. Similar to how APIs are utilized across various applications with entire businesses built around providing reliable API services, data contracts aim maintain the same level of stability and dependability.</p><p>Data contracts are typically specified using YAML as recommended by the Open Data Contract Standard (ODCS) [4]. YAML is preferred because:</p><p>- It’s version-control friendly</p><p>- It uses a human-readable format</p><p>- It can be directly leveraged by various tools</p><h3><strong>Motivation Behind Creation of Data Contracts</strong></h3><p>The concept of data contracts was formally introduced by Andrew Jones in 2021. In his white paper “Data Contracts 101,” he outlines the key problems that data contracts aim to solve [2]:</p><h4><strong>1. Lack of Collaboration between Data Producers and Consumers</strong></h4><p>Throughout his paper, Jones talks about how data producers — backend developers, product managers, etc. — are not fully aware of the business value of data or even the cost of bad data.</p><p>We need to understand one thing about data contracts — they make lives easier for data teams, but they mean more work and less freedom for product engineering teams. So it’s crucial for consumers to bring data producers onto the same page. Focus on the positive — why good data quality is important, why schema changes shouldn’t break existing processes, and how data either generates or saves actual money. For me, this seems to be the most important and difficult part. It’s vital to keep the tone in check; we don’t want to sound too demanding or bossy (“Enforce this schema!”). Rather, what we’re aiming for is fruitful collaboration.</p><p>So how does a data contract influence collaboration between data producers and consumers?</p><p>It’s simple — the whole process of creating and implementing data contracts requires teams to collaborate. A data contract generally consists of (as per [1]):</p><ul><li>Fundamentals — The basics like names, descriptions, etc.</li><li>Schema — Structure of data</li><li>Data quality — Accepted values, data governance policies (PII should be hashed)</li><li>Service-level agreement (SLA) — Refers to latency, retention, data freshness</li><li>Security &amp; stakeholders — Roles and responsibilities</li><li>Custom properties — Custom needs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7u6uwQefBfIWWMQKFBoO8A.png" /><figcaption>Source: PayPal</figcaption></figure><h3><strong>2. No Change Management for Schema Changes</strong></h3><p>It’s obvious that schemas will change as teams add new features, update functionality, or drop certain features for performance reasons. But these schema changes can lead to unwanted consequences downstream, like pipeline breakdowns, broken BI reports, or bad data fed to ML models. Data teams often find themselves just playing catch-up with these changes, and most of their time is invested in fixing issues rather than building actually useful applications.</p><p>Jatin Solanki’s article [3] summarizes how a typical CI/CD pipeline would look with a data contract integrated:</p><ol><li>Product engineering submits a pull request (PR) to implement any new changes made to the application</li><li>The PR is then reviewed by other team members — <strong>adding a data contract is like another set of checks that the code needs to pass</strong></li><li>This way, developers can avoid/restrain from making breaking changes.</li></ol><h3>Sample Data Contract</h3><p>Below you will find a sample data contract specifications file written in YAML. The data contract is for a customer profiles dataset in a retail application. The specification follows the Open Data Contract Standard (ODCS) with the sections that we discussed above.</p><p>Under the ODCS, there are 3 key components when specifying the schema in a data contract</p><ol><li><strong>Objects</strong> — These refer to the structures of data, it could be a table in a RDBMS or a document in a NoSQL DB.</li><li><strong>Properties — </strong>Attributes of the object, for instance the columns of a table are it’s properties.</li><li><strong>Elements — </strong>Refers to both objects and/or properties</li></ol><p>In our sample, the customers table is an object and it’s fields — customer_id, full_name, email, .etc are the properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b691bde554dcfaea440b557c5ae13061/href">https://medium.com/media/b691bde554dcfaea440b557c5ae13061/href</a></iframe><h3>Summary</h3><p>Data contract is an agreement between the data producing team and the data consuming team within an organisation. As per the creator of Data Contracts, Andrew Jones, it aims to solve two main issues</p><ul><li><strong>Lack of Collaboration between Data Producers and Consumers</strong></li><li><strong>No Change Management for Schema Changes</strong></li></ul><p>Data contracts are more than just a technical change, it demands cultural changes within an organisation and therefore the hard part about it is not the implementation and maintenance rather it’s getting the buy-in from the stakeholders.</p><p>Thanks for reading, if you find any errors please feel free to drop them in the comments!</p><h3><strong>References</strong></h3><p>[1] : <a href="https://github.com/paypal/data-contract-template">https://github.com/paypal/data-contract-template</a></p><p>[2] : <a href="https://andrew-jones.com/data-contracts-101/">https://andrew-jones.com/data-contracts-101/</a></p><p>[3] : <a href="https://blog.det.life/data-contracts-a-guide-to-implementation-86cf9b032065">https://blog.det.life/data-contracts-a-guide-to-implementation-86cf9b032065</a></p><p>[4] : <a href="https://github.com/bitol-io/open-data-contract-standard/tree/main">https://github.com/bitol-io/open-data-contract-standard/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d36221485bf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indexing Strategies That Work Across Platforms]]></title>
            <link>https://joyansbhathena.medium.com/indexing-strategies-that-work-across-platforms-ffcab7a64757?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcab7a64757</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 12:46:58 GMT</pubDate>
            <atom:updated>2025-04-05T12:46:58.262Z</atom:updated>
            <content:encoded><![CDATA[<p>Database indexing is a critical technique for optimizing query performance. Just as a book index helps you quickly find specific information without reading every page, database indexes allow the system to efficiently locate data without scanning entire tables. This article explores different types of indexes and presents a strategic approach shown by YouTuber Baraa Khatib Salkini, to implementing them effectively.</p><h3>Types of Database Indexes</h3><p>First let’s understand the different types of indexes you can create and which one to choose based on the use case. Note, the type of indexes depends on the specific platform but the following covered provide the necessary base for understanding them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ow26TISKju4ZabrI8e3HoQ.png" /></figure><h3>1. Clustered Index</h3><p>Clustered indexes physically sort and store data rows based on key values. Think of them as a phone book organized alphabetically — they determine the actual order of data storage. Key characteristics include:</p><ul><li>Limited to one per table, as data can only be sorted in one direction</li><li>Typically used for primary key columns or date columns</li><li>Directly alters the physical organization of the data</li></ul><h3>2. Non-clustered Index</h3><p>Non-clustered indexes create a separate structure containing key values and pointers to the actual data rows. Similar to a book index, they don’t change how the underlying data is stored but provide a quick reference to locate it. These indexes:</p><ul><li>Allow multiple indexes per table</li><li>Are ideal for foreign keys and frequently filtered columns</li><li>Create additional storage structures with pointers to actual data</li></ul><h3>3. Unique Index</h3><p>Unique indexes ensure data integrity by preventing duplicate values in the indexed columns:</p><ul><li>Enforce uniqueness constraints</li><li>Allow only one NULL value (if NULL values are permitted)</li><li>Often automatically created when defining unique or primary key constraints</li></ul><h3>4. Columnstore Index</h3><p>Unlike traditional row-based storage, columnstore indexes organize data by columns:</p><ul><li>Significantly improve compression rates</li><li>Excel at analytical queries involving aggregations</li><li>Process data more efficiently for large datasets</li><li>Optimize reporting and business intelligence workloads</li></ul><h3>5. Filtered Index</h3><p>Filtered indexes index only specific rows that meet defined conditions:</p><ul><li>Reduce index size and maintenance overhead</li><li>Improve query performance for specific subsets of data</li><li>Example: An index only on “active employees” rather than all employees</li></ul><h3>Four-Phase Indexing Strategy</h3><p>The indexing strategy outlined in this article was shared by data expert Baraa Khatib Salkini through his YouTube channel. I found his framework practical and simple to implement. The phase-wise break down makes it much more manageable and it can be applied to both new and existing database systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXu3rNLj2vqw-bHdatROjA.png" /><figcaption>Video — <a href="https://www.youtube.com/watch?v=0UxHG8zJ3F4&amp;ab_channel=DatawithBaraa">https://www.youtube.com/watch?v=0UxHG8zJ3F4&amp;ab_channel=DatawithBaraa</a></figcaption></figure><h3>Phase 1: Initial Indexing Strategy</h3><p>Begin by defining clear objectives for your indexing approach based on workload characteristics:</p><p><strong>For analytical systems (OLAP):</strong></p><ul><li>Prioritize read performance</li><li>Consider columnstore indexes for fact tables</li><li>Focus on columns frequently used in aggregations</li></ul><p><strong>For transactional systems (OLTP):</strong></p><ul><li>Balance read and write performance</li><li>Create clustered indexes on primary keys</li><li>Be cautious with additional indexes that might slow down writes</li></ul><p>Remember the golden rule - <strong>Less is More</strong>. Excessive indexes create maintenance overhead and can confuse the query optimizer, potentially degrading performance.</p><h3>Phase 2: Usage Pattern Analysis</h3><p>Analyze how your database is actually being used:</p><ul><li>Identify the most frequently accessed tables</li><li>Determine which columns appear most often in WHERE, JOIN, GROUP BY, and ORDER BY clauses</li><li>Select appropriate index types based on observed patterns</li><li>Test index effectiveness by comparing query performance metrics and execution plans</li></ul><h3>Phase 3: Scenario-Based Optimization</h3><p>Target specific high-impact queries that require optimization:</p><ol><li>Identify critical but slow-performing queries</li><li>Analyze execution plans to pinpoint bottlenecks</li><li>Apply specific indexes to address these bottlenecks</li><li>Validate performance improvements</li></ol><p>Remember that indexing is just one optimization technique — sometimes query rewrites or schema changes may be more appropriate solutions.</p><h3>Phase 4: Monitoring and Maintenance</h3><p>Implement ongoing monitoring and maintenance practices:</p><ul><li>Regularly check for duplicate or redundant indexes</li><li>Identify missing indexes that could improve performance</li><li>Monitor index usage to ensure they’re being utilized as expected</li><li>Update database statistics regularly to help the optimizer make better decisions</li><li>Consider index reorganization or rebuilding when fragmentation exceeds acceptable thresholds</li></ul><h3>Conclusion</h3><p>Effective database indexing requires balancing performance benefits against maintenance costs. By following this four-phase approach — establishing initial strategy, analyzing usage patterns, addressing specific scenarios, and implementing ongoing maintenance — you can develop an indexing strategy that significantly improves database performance while minimizing overhead.</p><p>Remember that indexing strategies should evolve with your application’s needs. Regular review and refinement of your indexes will ensure continued optimal performance as data volumes grow and query patterns change.</p><h3>Further Resources</h3><ul><li><a href="https://youtu.be/3G293is403I?si=SWALv97fYSjYl3TG">How do Indexes Work</a></li><li><a href="https://learn.microsoft.com/en-us/sql/relational-databases/indexes/indexes?view=sql-server-ver16">Index Types Documentation</a></li><li><a href="https://youtu.be/0UxHG8zJ3F4?si=Syi_GBGMDyaQm_wN">Baraa’s Indexing Strategy</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcab7a64757" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Storage Levels in Spark with Illustrations]]></title>
            <link>https://blog.devgenius.io/different-storage-levels-in-spark-with-illustrations-28c64720f1c2?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/28c64720f1c2</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 18:28:00 GMT</pubDate>
            <atom:updated>2025-03-10T22:13:34.598Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I would like to cover</p><ul><li>Why is it important</li><li>The different storage level options in spark</li><li>Serialization and Deserialization</li><li>Conclusion</li></ul><p>In Spark, the StorageLevel class allows you to decide how the RDD is stored / persisted.</p><p>Each StorageLevel specifies whether to:</p><ul><li>use memory</li><li>drop the RDD to disk if it falls out of memory</li><li>keep the data in memory in a JAVA-specific serialized format</li><li>replicate the RDD partitions on multiple nodes</li></ul><p>This article assumes that you have an understanding of Spark&#39;s memory layout, if not here are some resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*db-qY28h7J4byUKF0h-KZQ.png" /></figure><p><a href="https://youtu.be/sXL1qgrPysg?si=LNzRHdiEU8XmrvJ7">https://youtu.be/sXL1qgrPysg?si=LNzRHdiEU8XmrvJ7</a></p><p><a href="https://medium.com/@ashwin_kumar_/apache-spark-memory-management-fb13d1ad4492">https://medium.com/@ashwin_kumar_/apache-spark-memory-management-fb13d1ad4492</a></p><h3><strong>Why is it Important?</strong></h3><p>The type of storage level you choose to persist the data with, affects the performance greatly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*62bfFMbD1oxPOK_iGSBriQ.png" /></figure><p>Choosing the appropriate storage level in Spark is essential for optimizing performance, resource utilization, and fault tolerance in big data applications. Here are the key reasons why selecting the right storage level is important:</p><h4>1. Performance Optimization</h4><ul><li><strong>Faster Data Access</strong>: Some storage levels, such as MEMORY_ONLY, provide faster access by keeping data in memory, avoiding recomputation or disk I/O.</li><li><strong>Reduced Computation Overhead</strong>: Persisting frequently used data avoids recalculating RDDs or DataFrames during iterative algorithms or multiple actions on the same dataset.</li></ul><h4>2. Efficient Resource Utilization</h4><ul><li><strong>Memory Management</strong>: Storage levels like MEMORY_ONLY_SER and MEMORY_AND_DISK_SER use serialization to reduce memory usage, making them suitable for large datasets with limited memory.</li><li><strong>Disk Usage</strong>: Levels such as DISK_ONLY allow processing of datasets that do not fit into memory, trading speed for scalability.</li></ul><h4>3. Fault Tolerance</h4><ul><li><strong>Data Replication</strong>: Storage levels with replication (e.g., MEMORY_ONLY_2) ensure that data is available even if a node fails.</li><li><strong>Avoiding Data Loss</strong>: Levels like MEMORY_AND_DISK store data on disk if memory is insufficient, preventing recomputation or loss in case of memory overflow.</li></ul><h4>4. Trade-offs Between Speed and Cost</h4><ul><li>Different storage levels balance speed (e.g., MEMORY_ONLY) and cost (e.g., DISK_ONLY). Choosing the right level helps adapt to the application&#39;s specific needs and available resources.</li></ul><h4>5. Scalability</h4><ul><li>For large datasets that cannot fit entirely in memory, storage levels like MEMORY_AND_DISK or DISK_ONLY allow Spark to scale computations across distributed nodes efficiently.</li></ul><p>By carefully selecting a storage level based on dataset size, available resources, and application requirements, you can achieve optimal performance while avoiding unnecessary computational overhead or resource wastage.</p><h3><strong>Storage Levels in Spark</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*GPtKOs7g6yiBPAgdy2Ilvg.png" /><figcaption>Storage Levels in Spark — Made with Napkin AI</figcaption></figure><h4>1. <strong>MEMORY_AND_DISK(_n)</strong></h4><ul><li>Stores the RDD or dataframe as <em>deserialized</em> Java objects in the JVM Heap. (Serialisation and Deserialisation covered in the next section)</li><li>This level first tries to fill up the memory and then if there&#39;s still data remaining it will offload it to disk</li><li>With `_n` you can specify how many copies of replicas need to be created, for instance `MEMORY_AND_DISK_2` means 2 copies.</li></ul><h4>2. <strong>MEMORY_ONLY</strong></h4><ul><li>Stores RDD as <em>deserialized</em> Java objects in the JVM Heap</li><li>If the RDD does not fit in memory, some partitions will not be cached, leading to their re-computation every time they&#39;re needed</li></ul><h4>3. <strong>MEMORY_ONLY_SER</strong></h4><ul><li>Stores RDD as <em>serialized</em> Java objects in the JVM Heap</li><li>This is more space efficient than deserialized objects but a slightly greater overhead in CPU computation</li></ul><h4>4. <strong>MEMORY_AND_DISK_SER</strong></h4><ul><li>Similar to MEMORY_ONLY_SER but with the modification of spilling to disk when space runs out in memory.</li></ul><h4>5. <strong>DISK_ONLY</strong></h4><ul><li>Similar to MEMORY_ONLY_SER but with the modification of spilling to disk when space runs out in memory.</li></ul><h4>6. <strong>OFF_HEAP</strong></h4><ul><li>Stores the RDD as serialized objects in off-heap memory.</li></ul><h3><strong>Serialization and Deserialization</strong></h3><p><strong>Serialization</strong> is the process of converting an object&#39;s state(data) to a byte stream. This byte stream can then be saved to a file, sent over a network, or stored in a database.</p><p><strong>Deserialization</strong> is the reverse process of serialization. It involves taking a byte stream and converting it back into an object.</p><p><em>A byte stream is a sequence of bytes (8-bit integers) that represents data in its most basic, machine-readable format.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04Ko3CM-k9xLivPOxyJm1w.png" /></figure><h4><strong>Why Serialization?</strong></h4><p>In Apache Spark, serialization is used for:</p><ul><li>Storing data efficiently - Enables more compact data storage</li><li>Transferring data between nodes in a distributed system - Converting data to byte streams allows faster data transfer between cluster nodes</li><li>Caching and checkpointing</li></ul><p>There two options for serialization in Spark, but those are beyond the scope of this article. If you would like to read more on that then you can refer to Spark&#39;s documentation <a href="https://spark.apache.org/docs/latest/tuning.html#:~:text=Java%20serialization%3A%20By%20default%2C%20Spark,you%20create%20that%20implements%20java">here</a>.</p><h4><strong>Deserialized Data</strong></h4><ul><li>Stored in memory in its original, human-readable format</li><li>Easier to work with directly</li><li>Takes more memory space</li><li>Faster to process locally</li></ul><h4><strong>Serialized Data</strong></h4><ul><li>Converted to compact byte stream</li><li>Smaller memory footprint</li><li>Slower to access and process</li><li>Requires conversion back to original format before use</li></ul><h4><strong>Comparing Serialized Vs Deserialized Data in PySpark</strong></h4><pre>from pyspark.sql import SparkSession<br>from pyspark import StorageLevel<br>import time<br><br>def create_large_rdd(spark, size=100000):<br>    &quot;&quot;&quot;<br>    Create a large RDD with complex objects to demonstrate memory differences<br>    &quot;&quot;&quot;<br>    # Create a list of complex objects (dictionaries in this case)<br>    large_data = [<br>        {<br>            &#39;id&#39;: i, <br>            &#39;name&#39;: f&#39;User_{i}&#39;, <br>            &#39;details&#39;: {<br>                &#39;age&#39;: i % 100,<br>                &#39;score&#39;: i * 0.5,<br>                &#39;long_string&#39;: &#39;x&#39; * (i % 10 + 1)  # Variable length strings<br>            }<br>        } for i in range(size)<br>    ]<br>    <br>    return spark.sparkContext.parallelize(large_data, 8)  # Use 8 partitions<br><br>def main():<br>    # Create Spark Session<br>    spark = SparkSession.builder \<br>        .appName(&quot;SparkMemoryUsageComparison&quot;) \<br>        .config(&quot;spark.driver.memory&quot;, &quot;4g&quot;) \<br>        .getOrCreate()<br>    <br>    # Create large RDD and give it a name<br>    rdd = create_large_rdd(spark)<br>    rdd.setName(&quot;TestRDD-Serialized&quot;)<br>    <br> <br>    print(&quot;\n===== Testing MEMORY_AND_DISK (Serialized) =====&quot;)<br>    rdd.persist(StorageLevel.MEMORY_AND_DISK)<br>    count = rdd.count()  # Force computation and caching<br>    print(f&quot;RDD Count: {count}&quot;)<br>    <br>    # Take a small sample to ensure data is cached<br>    print(&quot;Sample data:&quot;, rdd.take(2))<br>    <br>    # Print storage level<br>    print(f&quot;Storage Level: {rdd.getStorageLevel()}&quot;)<br>    <br>    print(&quot;\nPlease check Spark UI at http://localhost:4040&quot;)<br>    print(&quot;Go to &#39;Storage&#39; tab and note the memory used&quot;)<br>    print(&quot;Waiting 15 seconds for you to check...&quot;)<br>    time.sleep(15)<br>    <br>    # Unpersist to clear cache<br>    rdd.unpersist()<br>    time.sleep(2)  # Give time for unpersist to complete<br>    <br>    # Create a new RDD with the same data but different name for comparison<br>    rdd2 = create_large_rdd(spark)<br>    rdd2.setName(&quot;TestRDD-Deserialized&quot;)<br>    <br>    <br>    print(&quot;\n===== Testing MEMORY_AND_DISK_DESER (Deserialized) =====&quot;)<br>    rdd2.persist(StorageLevel.MEMORY_AND_DISK_DESER)<br>    count = rdd2.count()  # Force computation and caching<br>    print(f&quot;RDD Count: {count}&quot;)<br>    <br>    # Take a small sample to ensure data is cached<br>    print(&quot;Sample data:&quot;, rdd2.take(2))<br>    <br>    # Print storage level<br>    print(f&quot;Storage Level: {rdd2.getStorageLevel()}&quot;)<br>    <br>    print(&quot;\nPlease check Spark UI at http://localhost:4040&quot;)<br>    print(&quot;Go to &#39;Storage&#39; tab and note the memory used&quot;)<br>    print(&quot;Compare with the previous memory usage&quot;)<br>    print(&quot;Waiting 15 seconds for you to check...&quot;)<br>    time.sleep(15)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Once you run this code, you should see something like this in Spark&#39;s UI Storage Tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvgSLeUUniZH07EHF6_6nQ.png" /></figure><p>1. <strong>TestRDD-Serialized</strong> (using MEMORY_AND_DISK):</p><ul><li>In PySpark MEMORY_AND_DISK Storage Level means</li><li>useMemory -&gt; True</li><li>useDisk -&gt; True</li><li>useOffHeap -&gt; False</li><li>deserialized -&gt; False (i.e. data is <strong>serialized</strong>)</li><li>Size in Memory: 1724.0 KiB</li></ul><p>2. <strong>TestRDD-Deserialized</strong> (using MEMORY_AND_DISK_DESER)</p><ul><li>Similarly MEMORY_AND_DISK_DESER Storage Level means</li><li>useMemory -&gt; True</li><li>useDisk -&gt; True</li><li>useOffHeap -&gt; False</li><li>deserialized -&gt; True (i.e. data is <strong>deserialized</strong>)</li><li>Size in Memory: 5.3 MiB</li></ul><h4><strong>Key Observations</strong></h4><ul><li>The deserialized data (5.3 MiB) takes approximately 3 times more memory than the serialized data (1724.0 KiB ≈ 1.7 MiB)</li><li>Both RDDs have 8 cached partitions (default parallelism) with 100% of the data cached</li></ul><h3><strong>Conclusion</strong></h3><p>Choosing the right storage level in Spark is a critical decision that directly impacts both memory usage and processing performance. As demonstrated in our comparison, serialized data consumes significantly less memory (about one-third in our example) but requires additional CPU resources for serialization and deserialization operations.</p><p>When deciding on the appropriate storage level for your application, consider these factors:</p><ul><li>Available memory across your cluster</li><li>CPU resources and processing requirements</li><li>The frequency of data access</li><li>The complexity and size of your dataset</li></ul><p>For memory-constrained environments, serialized storage options (MEMORY_ONLY_SER or MEMORY_AND_DISK_SER) offer better space efficiency. For CPU-bound applications where processing speed is paramount, deserialized options (MEMORY_ONLY or MEMORY_AND_DISK) might be preferable despite higher memory usage.</p><p>Remember that no single storage level is optimal for all scenarios. The best approach is to benchmark different storage options with your specific workload to find the right balance between memory usage, CPU overhead, and overall performance for your particular use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28c64720f1c2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/different-storage-levels-in-spark-with-illustrations-28c64720f1c2">Different Storage Levels in Spark with Illustrations</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shuffle Partitions and DataFrame Partitioning Are Not The Same]]></title>
            <link>https://blog.devgenius.io/shuffle-partitions-and-dataframe-partitioning-are-not-the-same-0a71b5385713?source=rss-8e218175ad95------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a71b5385713</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Joyan Bhathena]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 19:31:32 GMT</pubDate>
            <atom:updated>2025-02-24T20:16:52.650Z</atom:updated>
            <content:encoded><![CDATA[<p>Since starting my journey in data engineering, I have always heard this word ‘partition(ing)’ and for valid reasons. In simple terms, it is the method of segregating your data into buckets such that you can choose which bucket you want to process and thus save resources.</p><p>However, I did face trouble understanding the difference between Shuffle partitions (specific to Apache Spark) and partitioning a dataframe — with this article I hope to clear my doubts in the process and also share my learnings. Los geht’s.</p><h3>Quick Overview of Partitioning</h3><h4>What is Partitioning?</h4><p>It is a technique in which data is split logically into partitions such that each partition can be accessed separately.</p><h4>Why Partitioning?</h4><ul><li>Better performance — since you don’t need to process the complete dataset, you can pick a part of it</li><li>Allows scaling horizontally when the size of the data grows</li></ul><h3>1. Shuffle Partitions</h3><p>Now, what are shuffle partitions? Shuffle partitions are the partitions that are created in Apache Spark during a Shuffle operation.</p><p>Quick side note — Shuffle refers to the transfer of data from different nodes into a single destination to perform a certain action like aggregation or a join. However, the key thing to note here is that Shuffle is an expensive operation because you need to transfer data across the network.</p><h4>Important Spark Properties for Shuffle Partitions</h4><p>spark.sql.shuffle.partitions: The direct way to specify how many shuffle partitions you want, default value is 200. However, with the advent of Spark&#39;s AQE - Spark automatically coalesces this number when needed.</p><p><em>Adaptive Query Execution — an optimization technique in Spark SQL that makes use of the runtime statistics to choose the most efficient query execution plan</em></p><p>Note, AQE can only coalesce post-shuffle partitions and not increase the number of partitions.</p><h3>2. Input DataFrame Partitioning</h3><p>When you load a dataframe/dataset into Spark, then depending on the size of the data it is split into partitions for optimal processing. This also applies to when reading already partitioned data — 3 possible cases:</p><ol><li>Too large partition size =&gt; repartition to create smaller partitions</li><li>Too small partition size =&gt; coalesce to fewer, larger partitions</li><li>Optimal size =&gt; keep original partitioning</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JuLzupZ2JneI6ANWvXi-g.png" /><figcaption>Input DataFrame Partitioning</figcaption></figure><h4>Important Spark Properties for Input Partitioning</h4><p>spark.sql.files.maxPartitionBytes: Specifies the maximum size of a partition in terms of bytes. The default value is 128MB.</p><p>spark.sparkContext.defaultParallelism: It determines the number of partitions that Spark will use when processing data. This value is typically based on the number of available cores in your cluster or local machine.</p><h3>Real-World Example: Music Listening Activity Analysis</h3><p>Let’s look at a practical example to see how input partitions and shuffle partitions come into picture. I have a listening activity dataset that is partitioned by date:</p><pre>listening-activity-partitioned/<br>    listen_date=2023-04-26/<br>        part-00000-ff94d989-8ead-463e-a4c3-fb7e927ec517.c000.snappy.parquet<br>    listen_date=2023-04-27/<br>        part-00000-ff94d989-8ead-463e-a4c3-fb7e927ec517.c000.snappy.parquet<br>    ...</pre><p>Now when I load the whole partitioned parquet file into Spark, the output shows that despite having our data physically partitioned by date in storage, Spark has created 8 input partitions.</p><pre># Reading partitioned data<br>listening_df = spark.read.parquet(&quot;listening-activity-partitioned/&quot;)<br># Input partitioning: Spark automatically uses the date partitioning<br>print(f&quot;Number of input partitions: {listening_df.rdd.getNumPartitions()}&quot;)</pre><pre># Output:<br># Number of input partitions: 8</pre><p>The total data set size is 326.44 KB, which could easily be coalesced into a single partitions but due to spark minimum parallelism configuration, it is split into 8.</p><pre>print(spark.sparkContext.defaultParallelism)</pre><pre># Output:<br># 8</pre><p>Now, let’s see how shuffle partitions come into play when we perform a wide transformation like a group by</p><pre># Wide transformation: Finding average listening duration by hour<br>hourly_stats = listening_df.groupBy(&quot;listen_hour&quot;) \<br>    .agg(<br>        avg(&quot;listen_duration&quot;).alias(&quot;avg_duration&quot;),<br>        count(&quot;activity_id&quot;).alias(&quot;num_listens&quot;)<br>    ) \<br>    .orderBy(&quot;listen_hour&quot;)<br><br># Optimize shuffle partitions since our hourly aggregation will be small<br># Default number of shuffle partitions will be 200, we change it to 10<br>spark.conf.set(&quot;spark.sql.shuffle.partitions&quot;, 10)</pre><p>On examining the DAG for this transformation you will find that</p><ul><li>Exchange: This is where shuffling happens</li><li>Initially set to 10 partitions (our configuration)</li><li>AQE (Adaptive Query Execution) optimized it to just 1 partition</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*XtRYYDZkPIISi_qTE1Hy5A.png" /><figcaption>DAG for Wide transformation</figcaption></figure><h3>Key Takeaways</h3><ul><li>Input partitions are created when reading data into Spark and can be controlled using repartition() or coalesce().</li><li>Shuffle partitions are created when Spark shuffles data across nodes during wide transformations. You can set this value using spark.sql.shuffle.partitions</li></ul><p>I hope this article helped you understand the difference between shuffle partitions and dataframe partitions — it surely helped me!</p><h3>References</h3><p><a href="https://www.linkedin.com/feed/update/urn:li:activity:7108645278416527360?updateEntityUrn=urn%3Ali%3Afs_updateV2%3A%28urn%3Ali%3Aactivity%3A7108645278416527360%2CFEED_DETAIL%2CEMPTY%2CDEFAULT%2Cfalse%29">https://www.linkedin.com/feed/update/urn:li:activity:7108645278416527360</a></p><p><a href="https://spark.apache.org/docs/3.5.3/sql-performance-tuning.html">Performance Tuning</a></p><p><a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.html">https://spark.apache.org/docs/latest/api/python/reference/pyspark.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a71b5385713" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/shuffle-partitions-and-dataframe-partitioning-are-not-the-same-0a71b5385713">Shuffle Partitions and DataFrame Partitioning Are Not The Same</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>