<?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 Samantha Cruz on Medium]]></title>
        <description><![CDATA[Stories by Samantha Cruz on Medium]]></description>
        <link>https://medium.com/@sammcruz?source=rss-7d58fbcc818c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mnz9j97my0vr9x33ydCNHQ.png</url>
            <title>Stories by Samantha Cruz on Medium</title>
            <link>https://medium.com/@sammcruz?source=rss-7d58fbcc818c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 14:27:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sammcruz/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[Fabric Policies: A Practical Guide to Granular Governance in Microsoft Fabric]]></title>
            <link>https://sammcruz.medium.com/fabric-policies-a-practical-guide-to-granular-governance-in-microsoft-fabric-388e6655c91c?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/388e6655c91c</guid>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[microsoft-fabric]]></category>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 10:51:23 GMT</pubDate>
            <atom:updated>2026-10-17T10:51:23.896Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to roll out item creation, workspace settings and sharing rules without blocking your own teams.</em></p><p>If you administer Microsoft Fabric, you know the dilemma. Most governance controls are switches: a tenant setting is on or off, maybe delegated to a capacity or a workspace. Turn a feature on and everyone can use it. Leave it off and the teams who are ready have to wait for everyone else.</p><p>Fabric Policies, now in Preview, change that. Instead of a switch, you write rules: <em>this</em> security group can do <em>this</em> action in <em>these</em> workspaces. In this guide I explain how policies work, the trap that catches most people on day one, and a checklist to roll them out safely.</p><h3>What Fabric Policies are</h3><p>Fabric Policies are rule-based governance controls, <a href="https://community.fabric.microsoft.com/t5/Fabric-Updates-Blog/Build-deploy-and-govern-Microsoft-Fabric-at-scale/ba-p/5369145">announced at FabCon Europe</a> on September 30, 2026 and <a href="https://community.fabric.microsoft.com/t5/Fabric-Updates-Blog/Fabric-Policies-Granular-governance-at-scale-Preview/ba-p/5368144">explained in detail</a> on October 15. They are in Preview.</p><p>A few concepts are all you need:</p><ul><li><strong>Policy set.</strong> A Fabric item that holds your policies. It lives in a workspace, so it supports REST APIs, Git integration and CI/CD like any other item.</li><li><strong>Admin scope.</strong> Tenant or Capacity, chosen when you create the policy set. It can’t be changed later.</li><li><strong>Rules.</strong> Each rule has conditions, such as security group, workspace, item type or sensitivity label. All conditions in a rule must match.</li><li><strong>Effect.</strong> Today the only effect is Allow. Once you add rules, anything no rule allows is blocked.</li><li><strong>Activation.</strong> A policy does nothing until it’s activated. Only one policy set can be active per scope.</li></ul><p>One point is easy to miss: <strong>policies never grant access.</strong> A user still needs the normal workspace role or item permission. The policy adds a second check on top.</p><h3>How Fabric evaluates a policy</h3><p>Every governed action goes through the same check. Normal permissions come first, then Fabric loads the one active policy for the scope and looks for a rule that allows the action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28NmtUBhzFvg1kAKBWnHCQ.png" /><figcaption><em>How Fabric evaluates a governed action. Diagram by the author, based on </em><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-overview"><em>Microsoft Learn</em></a><em>.</em></figcaption></figure><p>Four pieces of logic explain every result:</p><ul><li>Conditions inside a rule are combined with <strong>AND</strong>: all of them must match.</li><li>Separate rules are combined with <strong>OR</strong>: one matching rule is enough.</li><li>Values inside one condition work as OR too: <em>Is any of</em> matches when at least one value matches, <em>Is none of</em> when none do.</li><li>A condition you leave out matches everything. A rule with no workspace condition applies to every workspace in its scope.</li></ul><h3>The three policy types</h3><p>There are three policy types today. Each has a fixed scope and a default that applies until you add rules.</p><ul><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-item-creation"><strong>Allow item creation</strong></a> (Capacity scope, activated by a capacity admin). Controls who can create which item types, in which workspaces. Default: allow all item types.</li><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-edit-workspace-settings"><strong>Allow workspace settings editing</strong></a> (Tenant scope, activated by a Fabric admin). Controls which workspace admins can change selected security settings. Default: allow editing all settings.</li><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-external-data-sharing"><strong>Allow external data sharing</strong></a> (Tenant scope, activated by a Fabric admin). Controls who can share data externally, from which workspaces, and with which email domains. Default: block all. Coming soon.</li></ul><p><strong>Item creation</strong> is the one I’d start with. A capacity admin can let the Data Engineering group create Dataflow Gen2 items only in the data platform workspaces, and the AI team create Data agents only in AI workspaces. This makes a gradual rollout possible: enable a new item type for one team first, not the whole capacity.</p><p><strong>Workspace settings</strong> protects settings like inbound and outbound access protection and customer-managed keys (CMK). Central IT can keep those, while other workspace admins still manage everything else.</p><p><strong>External data sharing</strong> will let you allow, for example, the Finance group to share Confidential items from Finance workspaces with one partner domain only.</p><p>Watch the difference between the two. External sharing is allowed if <em>either</em> the existing External data sharing tenant setting <em>or</em> a policy rule allows it. Item creation is the opposite: the item type’s tenant setting <em>and</em> the policy must both allow it.</p><h3>The trap: one rule turns it into an allow list</h3><p>This is the part that surprises people. An item creation policy starts as <em>Allowed</em>. Switch it to <em>Advanced (Set by user)</em> and add a single Allow rule, and <strong>every item type that no rule matches is blocked</strong> as soon as the policy set is active (within up to 15 minutes). Editing an inactive policy set is safe. The real risk is changing rules on one that’s already active.</p><p>Say you only want to control Dataflow Gen2 in production. Rule 1 alone would block every other item, in every workspace on the capacity. Microsoft’s own example adds a second rule to keep everything outside production open:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fv40XlCTbKYLvrMqEGJt2g.png" /><figcaption><em>Four requests against the same two rules. Diagram by the author, based on the example in </em><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-overview"><em>Microsoft Learn</em></a><em>.</em></figcaption></figure><p>Look at the third request. Even a member of the approved group can’t create a Notebook in production, because no rule allows it. If your production workspaces need notebooks, lakehouses and pipelines too, each one needs a rule.</p><h3>Getting started, step by step</h3><p>This is the path I’d follow for a first item creation policy. Microsoft’s <a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-get-started">get started guide</a> has the full detail.</p><ol><li><strong>Check your capacity region.</strong> Policies aren’t supported yet for capacities in West Europe, North Europe and West US. If yours is one of them, you’ll have to wait.</li><li><strong>Enable the tenant setting.</strong> Turn on <em>Policies</em> in OneLake catalog &gt; Govern &gt; Configurations (filter by “Policies”). The blog gives Admin portal &gt; Tenant settings instead. You can limit it to security groups, or exclude some.</li><li><strong>Create a secured admin workspace.</strong> It must be assigned to a Fabric capacity, and you need Contributor or higher to create a policy set. Keep its roles tight: Contributors and Members can edit rules, and only activation needs an admin.</li><li><strong>Create a policy set.</strong> Choose <strong>Fabric tenant</strong> or <strong>A capacity</strong> as its scope. You pick the exact capacity later, at activation. The name can’t contain spaces, and the scope can’t be changed.</li><li><strong>List every scenario that must keep working.</strong> Every group, item type and workspace combination. Write one rule per scenario.</li><li><strong>Choose Allowed, Blocked or Advanced (Set by user)</strong> for the policy. Advanced is where you add your rules.</li><li><strong>Review before activating.</strong> An inactive policy enforces nothing, so check every rule and every affected group first.</li><li><strong>Activate on a non-production capacity first.</strong> A capacity admin activates capacity scope, a Fabric admin activates tenant scope. Changes take up to 15 minutes.</li><li><strong>Test with real accounts.</strong> After 15 minutes, check that a user who matches a rule is allowed and a user who doesn’t is blocked.</li><li><strong>Monitor.</strong> Active policies show in OneLake catalog &gt; Govern &gt; Policies center. Each allow or deny decision is recorded in the Fabric audit logs, the place to debug a blocked user. Changes to policy sets and rules show in the Microsoft 365 audit log.</li></ol><p>For several environments or capacities, automate it. Policy sets can be managed with the <a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-rest-api">Fabric REST APIs</a> and Git. One exception: activation can’t happen through Git, only in the UI or through the API.</p><h3>Check these before you roll out</h3><ul><li><strong>Power BI items.</strong> Microsoft’s blog says Power BI item creation isn’t enforced yet, so don’t rely on a policy to block reports or semantic models.</li><li><strong>API names, not UI names.</strong> Item types in rules use their API identifiers. The UI’s “Pipeline” is DataPipeline.</li><li><strong>Workspace IDs, not names.</strong> Workspace conditions take the workspace GUID. A workspace that moves to another capacity falls under that capacity’s policy, so review coverage when that happens.</li><li><strong>Limits.</strong> Up to 50 rules per capacity policy, 100 per tenant policy, and 50 values per condition.</li><li><strong>Item creation needs two yeses.</strong> The item type’s own tenant setting and the policy must both allow it.</li><li><strong>Cost.</strong> Policies are included in your Fabric license and don’t consume capacity units.</li></ul><h3>Final thoughts</h3><p>Fabric Policies are still in Preview, so I’m testing them on non-production capacities first. But the direction is right. Governance stops being “everyone or no one” and starts matching how teams actually work: who you are, where you work and what you’re creating.</p><p>My advice: start with one item creation policy on one capacity, write down every scenario before you switch to Advanced, and test with real users before you activate.</p><p>Have you tried Fabric Policies yet? Which scenario would you govern first?</p><h3>Sources</h3><ul><li><a href="https://community.fabric.microsoft.com/t5/Fabric-Updates-Blog/Build-deploy-and-govern-Microsoft-Fabric-at-scale/ba-p/5369145">Build, deploy, and govern Microsoft Fabric at scale</a> (Fabric Updates Blog, September 30, 2026)</li><li><a href="https://community.fabric.microsoft.com/t5/Fabric-Updates-Blog/Fabric-Policies-Granular-governance-at-scale-Preview/ba-p/5368144">Fabric Policies: Granular governance at scale (Preview)</a> (Fabric Updates Blog, October 15, 2026)</li><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-overview">Microsoft Fabric policies: Centralized governance</a> (Microsoft Learn)</li><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-item-creation">Control item creation on a Fabric capacity</a> (Microsoft Learn)</li><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-get-started">Get started with Fabric policies</a> (Microsoft Learn)</li><li><a href="https://learn.microsoft.com/en-us/fabric/governance/fabric-policies-rest-api">Automate Fabric policies with the REST APIs</a> (Microsoft Learn)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=388e6655c91c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Ways to Make Your GitHub Copilot Credits Count]]></title>
            <link>https://sammcruz.medium.com/8-ways-to-make-your-github-copilot-credits-count-5cf95b439e8d?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf95b439e8d</guid>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 18:24:35 GMT</pubDate>
            <atom:updated>2026-06-20T18:24:35.733Z</atom:updated>
            <content:encoded><![CDATA[<p>If you use GitHub Copilot every day, you’ve probably noticed that not every AI interaction costs the same. A quick autocomplete is free. A long chat session pulling in five files is not. As a data manager overseeing a team of data engineers who rely on Copilot daily for our Microsoft Fabric and Azure work, I’ve started paying closer attention to how we use our credits, not just how much we use.</p><p>I recently came across a guide Microsoft put out for students on getting the most out of their Copilot credits. It was written for learners just starting out, but most of the advice applies just as much, if not more, to professional teams running production pipelines every day. Here are the eight habits worth adopting.</p><h4>1. Tab before chat</h4><p>Autocomplete and Next Edit Suggestions don’t consume AI credits on paid plans. This is the single most impactful habit you can build: try autocomplete first, every time, before opening a chat window. A huge share of small fixes (a missing import, a repetitive pattern, a type correction) don’t need a conversation at all.</p><h4>2. Default to a lighter model, escalate on purpose</h4><p>Not every task needs a frontier or reasoning-heavy model. Save those for the moments that genuinely call for deep reasoning, complex refactoring, or architectural decisions. For the bulk of day-to-day work, a lighter or auto-selected model gets the job done for a fraction of the cost.</p><h4>3. Context is the real cost driver, not message count</h4><p>This is the one that surprises people most. It’s not how many messages you send that drives cost, it’s how much context comes along with each one. Every open file, every extra tool, every paragraph of background gets resent as input on every turn. A focused question scoped to one file or one function costs very little. Pulling in the whole repository costs a lot, every single time you hit send.</p><h4>4. New task, new chat</h4><p>Carrying a long, unrelated conversation thread into a new problem means you’re paying to resend all that stale context before you’ve even asked your real question. Starting fresh keeps each session lean and relevant.</p><h4>5. Plan before you build</h4><p>A short, focused planning exchange that nails down the right approach is cheaper than fifty messages of trial and error after starting in the wrong direction. Spending a few extra minutes upfront to agree on the plan pays for itself quickly.</p><h4>6. Keep your instructions file short</h4><p>Anything written into a custom instructions file (like a copilot-instructions.md) runs on every single prompt you send. It’s not a one-time cost, it’s a recurring one. A bloated instructions file quietly taxes every interaction your team has with Copilot.</p><h4>7. Let deterministic tools do deterministic work</h4><p>Linters, compilers, type checkers, and formatters are free, fast, and reliable. If a linter can catch a missing import or a syntax error, let it. Save the AI reasoning for the problems that actually require judgment, not the ones a standard tool already solves.</p><h4>8. Stay engaged with your own code</h4><p>Beyond the cost angle, treating Copilot as a collaborator rather than an autopilot matters. Engineers who stay engaged with what the AI is suggesting build better instincts over time, and that translates into fewer expensive cleanup sessions down the line when something AI-generated needs to be unwound.</p><h4>Why this matters for engineering teams</h4><p>None of this is about using AI less. It’s about using it with intent, the same way we’d manage any other resource on an engineering team. A few of these habits, especially scoping context tightly, defaulting to lighter models, and keeping instructions files lean, scale directly with team size. The bigger your team and the more you lean on Copilot daily, the more these small habits add up.</p><h4>Source</h4><p>This article was inspired by a piece Microsoft published for students: “Make Your Copilot Credits Count: A Student’s Guide to Smarter AI Usage,” available at https://techcommunity.microsoft.com/blog/educatordeveloperblog/make-your-copilot-credits-count-a-students-guide-to-smarter-ai-usage/4526668. The tips have been adapted here for professional engineering teams on paid Copilot plans.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf95b439e8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slowly Changing Dimensions: A Complete Guide to All 8 Types (With Examples)]]></title>
            <link>https://sammcruz.medium.com/slowly-changing-dimensions-a-complete-guide-to-all-8-types-with-examples-285e36c6bc16?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/285e36c6bc16</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 09:01:02 GMT</pubDate>
            <atom:updated>2026-06-07T06:26:22.450Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked in data engineering for more than a week, you have heard of SCD. Everyone knows Type 1 and Type 2. But most tutorials stop there.</p><p>There are actually <strong>8 types of Slowly Changing Dimensions</strong>, each solving a different problem. Knowing when to use each one is crucial when defining your data architecture.</p><p>This article walks through all 8 types: what each one does, when to use it, how it looks in practice, and what breaks when you pick the wrong one.</p><h3>What Is a Slowly Changing Dimension?</h3><p>A dimension is a table that describes your business entities: customers, products, employees, locations. A slowly changing dimension is a dimension where those attributes change over time.</p><p>The core question is: when an attribute changes, what do you do with the old value?</p><p>Do you overwrite it? Keep both versions? Move the history somewhere else? Your answer determines which SCD type to use, and it has real consequences for your analytics.</p><p>We will use a simple example throughout: a customer named Ana who changes her city from Barcelona to Amsterdam, and later her membership tier from Silver to Gold.</p><h3>Type 0: Retain Original (Fixed)</h3><p>Type 0 means the attribute never changes. Once set, it stays forever, regardless of what happens in the source system.</p><p>When to use it: attributes that represent the original state of an entity and should never be overwritten. Think: a customer’s original signup date, their first country of registration, or a date dimension.</p><p>Example: Ana signed up in 2019. Her original_signup_country = ‘Spain’. Even if she moves, lives in German, and uses a German IP, this value stays Spain forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*WTw2add7Nwz1ioR3pfFmeQ.png" /></figure><h3>Type 1: Overwrite</h3><p>The simplest approach. When an attribute changes, overwrite the old value with the new one. No history is kept.</p><p>Before: customer_id=1, name=’Ana’, city=’Barcelona’, tier=’Silver’</p><p>After Ana moves: customer_id=1, name=’Ana’, city=’Amsterdam’, tier=’Silver’</p><pre><br># SCD Type 1: simple UPDATE — overwrites the old value, no history<br>from delta.tables import DeltaTable<br><br>delta_table = DeltaTable.forName(spark, &#39;dim_customer&#39;)<br><br>delta_table.update(<br>    condition = &quot;customer_id = 1&quot;,<br>    set = {&quot;city&quot;: &quot;&#39;Amsterdam&#39;&quot;}<br>)<br># Ana&#39;s old city &#39;Barcelona&#39; is gone forever</pre><p>When to use it: attributes where history is irrelevant. Correcting a typo in a name. Updating a phone number. Fixing a wrong category assignment.</p><p>What breaks if you overuse it: any historical report that asks ‘what city were our customers in when they placed this order?’ will be wrong. Your past facts will be attributed to the current state of the dimension, not the state at the time of the event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*JhVA12rcQ3cHMvMD3nnYNw.png" /></figure><h3>Type 2: Add a New Row</h3><p>The most widely used type. When an attribute changes, keep the old row and add a new one. Both versions coexist in the table.</p><p>Each row gets a surrogate key, an effective date, an expiry date, and a current_flag:</p><p>Row 1: surrogate_key=101, customer_id=1, city=’Barcelona’, valid_from=’2019–01–01&#39;, valid_to=’2024–06–01&#39;, is_current=0</p><p>Row 2: surrogate_key=102, customer_id=1, city=’Amsterdam’, valid_from=’2024–06–01&#39;, valid_to=’9999–12–31&#39;, is_current=1</p><pre><br><br>MERGE INTO dim_customer AS target<br>USING source_updates AS source<br>  ON target.customer_id = source.customer_id<br>  AND target.is_current = 1<br>WHEN MATCHED AND target.city &lt;&gt; source.city THEN<br>  UPDATE SET<br>    target.valid_to   = source.updated_at,<br>    target.is_current = 0<br>WHEN NOT MATCHED THEN<br>  INSERT (customer_id, name, city, valid_from, valid_to, is_current)<br>  VALUES (source.customer_id, source.name, source.city,<br>          source.updated_at, &#39;9999-12-31&#39;, 1);</pre><p>When to use it: any time you need to answer ‘what was the state of this dimension at the time of this fact?’ Sales reports, financial analysis, compliance audits.</p><p>The trap: forgetting to close the old record (set valid_to and flip is_current=0). If you forget, every query joining on is_current=1 returns duplicates. Silently wrong results. Or not silently, depending on your downstream use of this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*J_ZlvSfarXKhVluaZjr4aA.png" /></figure><h3>Type 3: Add a New Column</h3><p>Instead of a new row, you add a new column to track the previous value alongside the current one.</p><p>customer_id=1, name=’Ana’, previous_city=’Barcelona’, current_city=’Amsterdam’, tier=’Silver’</p><p>When to use it: when you only ever need to track one previous value and the table is wide enough to handle extra columns. Useful for simple what-changed reports.</p><p>The hard limit: if Ana moves a third time (Amsterdam to Berlin), you cannot store all three cities without adding yet another column. Type 3 only tracks one change back, by design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*R8Fe_-e2s67OjDjy73Yuxw.png" /></figure><h3>Type 4: Add a History Table (Mini-Dimension)</h3><p>Type 4 splits the dimension in two: a main table holds current data, and a separate history table stores every past version with timestamps.</p><p>Main table: customer_id=1, name=’Ana’, city=’Amsterdam’, tier=’Silver’</p><p>History table: customer_id=1, city=’Barcelona’, valid_from=’2019–01–01&#39;, valid_to=’2024–06–01&#39;</p><p>When to use it: when you have a large dimension with a mix of stable and frequently-changing attributes. Pull the volatile ones into a mini-dimension to avoid bloating the main table with endless Type 2 rows.</p><p>In practice: imagine a customer dimension with 100 million rows. Storing full history with Type 2 could mean 300 million rows. Type 4 keeps your main dimension lean and fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*12MDvglgBiy9pGgkbfrhNw.png" /></figure><h3>Type 5: Mini-Dimension with Current Profile Outrigger (Type 4 + 1)</h3><p>Type 5 builds on Type 4 by embedding a reference to the current mini-dimension profile directly in the base dimension. The name comes from the math: 4 + 1 = 5.</p><p>This solves a query performance problem. With pure Type 4, to get current attribute values you have to join through the fact table. Type 5 lets you query current attributes directly from the base dimension without that join.</p><p>The outrigger key in the base dimension always points to the current mini-dimension row. Your ETL process updates this key whenever the mini-dimension changes.</p><p>When to use it: large, frequently-queried dimensions where you often need both historical and current attribute values in the same report, and join performance matters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*cq7SnadjV8Tb-33XbZuj-w.png" /></figure><h3>Type 6: Combined Approach (Type 1 + 2 + 3)</h3><p>Type 6 is named after the math: 1 + 2 + 3 = 6. It combines all three basic types into one row structure. You get new rows for each change (Type 2), a column for the previous value (Type 3), and the current value is overwritten across all historical rows (Type 1).</p><p>This gives you maximum flexibility: you can report on what was true historically, what is true now, and what changed in one single join.</p><p>Row 1: surrogate_key=101, customer_id=1, city=’Barcelona’, current_city=’Amsterdam’, valid_from=’2019–01–01&#39;, valid_to=’2024–06–01&#39;, is_current=0</p><p>Row 2: surrogate_key=102, customer_id=1, city=’Amsterdam’, current_city=’Amsterdam’, valid_from=’2024–06–01&#39;, valid_to=’9999–12–31&#39;, is_current=1</p><p>Notice that current_city=’Amsterdam’ appears in BOTH rows. When Ana moves again, all rows get updated with the new current_city value.</p><p>When to use it: when your reports need to slice data both by the historical state at event time AND the current state of the customer, without reprocessing facts.</p><p>The cost: ETL complexity and more storage. Every attribute change triggers updates across all previous rows for that entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*9TgTSJzhCk0JwYUVKQJuoA.png" /></figure><h3>Type 7: Dual Type 1 and Type 2 (Surrogate + Natural Key)</h3><p>Type 7 delivers the same analytical power as Type 6 but through a different mechanism: instead of storing current values in each historical row, the fact table carries two foreign keys.</p><p>The first key is a surrogate key pointing to the Type 2 dimension row (the historical version at event time). The second key is the natural/durable key pointing to the current active row.</p><p>Fact table: order_id=9001, order_date=’2022–03–15&#39;, customer_surrogate_key=101 (historical), customer_natural_key=1 (durable)</p><p>Join by surrogate key: get Ana’s city as it was in 2022 (Barcelona). Join by natural key: get Ana’s city today (Amsterdam). Same fact row, two different views.</p><p>When to use it: when you want Type 6 flexibility without touching existing historical rows on every update. Preferred in systems where immutability of historical data is important.</p><p>The tradeoff: no database-level referential integrity on the natural key join, so your ETL must ensure consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*QqftTqiRWyioaVTG7RjGqg.png" /></figure><h3>How to Choose the Right Type</h3><p>Most real-world dimension tables use a mix of types applied to different columns. Here is a practical decision guide:</p><ul><li>Do you need no history at all? Use Type 1. Is this an immutable original attribute? Use Type 0.</li><li>Do you need full history for point-in-time accuracy? Use Type 2. This covers 90% of production use cases.</li><li>Do you need exactly one previous value, simply? Use Type 3. Accept the single-change limit.</li><li>Is your dimension massive and certain attributes change frequently? Use Type 4 to offload volatile attributes to a mini-dimension.</li><li>Do you need current attribute values without joining through fact tables? Add Type 1 on top of Type 4. That gives you Type 5.</li><li>Do you need both historical and current values from the same join, without dual keys? Use Type 6.</li><li>Do you need both views but want immutable historical rows? Use Type 7 with dual foreign keys.</li></ul><p>The most important rule: match different columns in the same dimension to different types. Customer name might be Type 1 (typo corrections are fine to overwrite). Customer city might be Type 2 (you need point-in-time accuracy for revenue attribution). Customer signup country might be Type 0 (never change it).</p><p>SCD types are not a test question. They are a design decision with real consequences. I have seen teams spend weeks debugging wrong historical reports because someone defaulted to Type 1 on a field that needed Type 2.</p><p>Pick the right type before you build. It is very hard to fix after the data has been accumulating for months.</p><p>If you found this useful, follow me for more data engineering fundamentals. I post here on Medium and on LinkedIn as part of my Data Engineer Nuggets series.</p><h3>References and Further Reading</h3><p>These are the authoritative sources for SCD theory and implementation:</p><ol><li>Kimball Group Design Tips on SCD Types 0, 4, 5, 6 and 7: <a href="https://www.kimballgroup.com/2013/02/design-tip-152-slowly-changing-dimension-types-0-4-5-6-7/">https://www.kimballgroup.com/2013/02/design-tip-152-slowly-changing-dimension-types-0–4–5–6–7/ </a>. Ralph Kimball defined most of these types. This is the primary reference for any serious data warehouse practitioner.</li><li>Azure Databricks Documentation on enabling history tracking: <a href="https://learn.microsoft.com/en-us/azure/databricks/ingestion/lakeflow-connect/scd">https://learn.microsoft.com/en-us/azure/databricks/ingestion/lakeflow-connect/scd</a> — Practical guide to implementing Type 2 in Azure Databricks.</li><li>dbt Documentation on Snapshots (SCD Type 2 in practice): <a href="https://docs.getdbt.com/docs/build/snapshots">https://docs.getdbt.com/docs/build/snapshots</a>. The most widely-used open-source implementation of SCD Type 2 in modern data stacks. Shows real SQL patterns.</li><li>Microsoft Azure Synapse Analytics documentation on SCD patterns: <a href="https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-tables-overview">https://learn.microsoft.com/en-us/azure/synapse-analytics/sql-data-warehouse/sql-data-warehouse-tables-overview</a> — Production-grade guidance on implementing SCDs at scale in cloud data warehouses.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=285e36c6bc16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Fabric Data Days]]></title>
            <link>https://sammcruz.medium.com/microsoft-fabric-data-days-70cdb0076763?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/70cdb0076763</guid>
            <category><![CDATA[data-fabric]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 15:11:40 GMT</pubDate>
            <atom:updated>2025-11-24T15:11:40.567Z</atom:updated>
            <content:encoded><![CDATA[<p>Microsoft launched <em>Fabric Data Days</em>, a 50-day initiative packed with sessions, challenges and guided learning. It covers the entire Fabric ecosystem, but if you work in data engineering, this edition is especially relevant.</p><p>Below is a concise guide to the sessions that matter, the requirements to earn free certification vouchers and all links you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*4VgFGiTMslnKJ5jqk7eaeg.png" /></figure><h3>What Is Fabric Data Days?</h3><p>Fabric Data Days is a 50-day community event organized by Microsoft and contributors worldwide. It includes:</p><ul><li>Live sessions</li><li>On-demand recordings</li><li>Workshops</li><li>Community challenges</li><li>Study groups</li><li>Certification preparation</li><li>Special contests and digital badges 📛</li></ul><p>The initiative is designed to help professionals progress in analytics, engineering and governance in the Microsoft Fabric platform.</p><p><strong>Fabric Data Days started on November 4th, and you still have 29 days before it ends!</strong></p><h3>Key Sessions for Data Engineers</h3><p>Here are the items in the schedule that directly benefit a data engineer.<br>All past sessions are available on YouTube. Just follow the URL on MS official page.</p><p><strong>Nov 11 — “So You Want to Be a Data Engineer”</strong><br> Overview of the role, career path and Fabric-specific responsibilities.</p><p><strong>Nov 12 — “From PL-300 to DP-600: Level Up Your Analytics Skills”</strong><br> Bridge between analytics and advanced engineering workloads.</p><p><strong>Hands-on Labs and Challenges:</strong></p><ul><li><strong>November 14</strong> — DP-600 Labs Series #1: Create a Microsoft Fabric Lakehouse</li><li><strong>November 15</strong> — DP-600 Labs Series #2: Create a medallion architecture in a Microsoft Fabric lakehouse</li><li><strong>November 17</strong> — Data Warehousing in Fabric</li></ul><p>And much more…</p><p>Full schedule here with past sessions recordings:<br> 👉 <a href="https://community.fabric.microsoft.com/t5/Power-BI-Community-Blog/Fabric-Data-Days-Full-Schedule/ba-p/4863778">Fabric Data Days | Full Schedule</a></p><h3>Voucher Eligibility and What You Need to Do</h3><p>If you want a <strong>100% discount voucher</strong> for exam DP‑600, DP‑700 or a 50% discount for exams PL-300 or DP-900 as part of Fabric Data Days, here are the clear steps:</p><ul><li>Register for Fabric Data Days via the official campaign page.</li><li>Attend at least one live session (or watch it on-demand) during the event window.</li><li>Join a skills challenge tied to the certification you want. <br><em>Challenges are active from October 27 until December 16, 2025.</em></li><li>Request your voucher via the registration/request form once eligibility is met.</li><li>Book and take the exam within the timeframe specified in the offer.</li></ul><p>Good luck 🍀 and comment here if you applied to earn your voucher! I’ve registered for the DP-900 since it’s the only one I don’t have yet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70cdb0076763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key Metrics to Evaluate LLMs]]></title>
            <link>https://sammcruz.medium.com/key-metrics-to-evaluate-llms-a9f4eb19f159?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f4eb19f159</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[llm-evaluation-metrics]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Wed, 14 May 2025 16:15:02 GMT</pubDate>
            <atom:updated>2025-05-14T16:15:02.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you know what are the most common metrics to evaluate Large Language Models (LLMs)?</p><p>Whether you’re fine-tuning a model, comparing outputs, or building an app powered by generative AI, knowing how to <em>score</em> your model is crucial. Each metric gives you a different angle on performance. In this article, I will show you the 10 most common evaluation metrics used to assess LLMs, when to use them, and where to dig deeper with some good references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*WKnD12NmXg37IFic" /></figure><h4>1. Perplexity</h4><ul><li><strong>Purpose</strong>: Measures how well a language model predicts a sample. Lower perplexity indicates better predictive performance.</li><li><strong>Application</strong>: Commonly used during training to assess model fluency and general language modeling capabilities.</li><li><strong>Reference</strong>: <a href="https://blog.uptrain.ai/decoding-perplexity-and-its-significance-in-llms/">Decoding Perplexity and its significance in LLMs</a></li></ul><h4>2. BLEU (Bilingual Evaluation Understudy)</h4><ul><li><strong>Purpose</strong>: Evaluates the precision of machine-generated translations by comparing n-gram overlaps with reference translations.</li><li><strong>Application</strong>: Primarily used for machine translation tasks.</li><li><strong>Reference</strong>: <a href="https://aclanthology.org/P02-1040.pdf"><em>BLEU: a Method for Automatic Evaluation of Machine Translation</em>.</a></li></ul><h4>3. ROUGE (Recall-Oriented Understudy for Gisting Evaluation)</h4><ul><li><strong>Purpose</strong>: Measures recall by evaluating the overlap of n-grams between the generated text and reference summaries.</li><li><strong>Application</strong>: Widely used for summarization tasks.</li><li><strong>Reference</strong>: <a href="https://aclanthology.org/W04-1013.pdf"><em>ROUGE: A Package for Automatic Evaluation of Summaries</em>.</a></li></ul><h4>4. METEOR (Metric for Evaluation of Translation with Explicit ORdering)</h4><ul><li><strong>Purpose</strong>: Considers precision, recall, synonymy, and stemming to evaluate translation quality.</li><li><strong>Application</strong>: Offers a more nuanced assessment than BLEU, especially for translations.</li><li><strong>Reference</strong>: <a href="https://aclanthology.org/W05-0909.pdf"><em>METEOR: An Automatic Metric for MT Evaluation with Improved Correlation with Human Judgments</em>.</a></li></ul><h4>5. BERTScore</h4><ul><li><strong>Purpose</strong>: Uses contextual embeddings from BERT to evaluate the semantic similarity between generated and reference texts.</li><li><strong>Application</strong>: Effective for tasks requiring semantic understanding, such as paraphrasing and summarization.</li><li><strong>Reference</strong>: <a href="https://openreview.net/forum?id=SkeHuCVFDr"><em>BERTScore: Evaluating Text Generation with BERT</em>.</a></li></ul><h4>6. Human Evaluation</h4><ul><li><strong>Purpose</strong>: Involves human judgments to assess aspects like fluency, coherence, and relevance.</li><li><strong>Application</strong>: Essential for evaluating tasks where automated metrics fall short, such as open-ended text generation.</li><li><strong>Reference</strong>: <a href="https://aclanthology.org/Q19-1021.pdf"><em>A Data-Driven Classification of Evaluation Metrics for Natural Language Generation</em>.</a></li></ul><h4>7. Latency</h4><ul><li><strong>Purpose</strong>: Measures the time taken by the model to generate a response.</li><li><strong>Application</strong>: Critical for real-time applications where response time impacts user experience.</li><li><strong>Reference</strong>: <a href="https://www.taivo.ai/__llm-latency-is-linear-in-output-token-count/"><em>LLM latency is linear in output token count.</em></a></li></ul><h4>8. Throughput</h4><ul><li><strong>Purpose</strong>: Assesses the number of tasks or tokens processed by the model per unit time.</li><li><strong>Application</strong>: Important for evaluating the efficiency and scalability of LLMs in production environments.</li><li><strong>Reference</strong>: <a href="https://brainhub.eu/library/how-to-measure-throughput"><em>How to Measure Throughput for Maximum Results</em></a></li></ul><h4>9. Exact Match (EM)</h4><ul><li><strong>Purpose</strong>: Measures whether the generated response matches the expected answer exactly, word-for-word.</li><li><strong>Application</strong>: Commonly used in question answering and information extraction tasks, especially when answers are short and precise (e.g., yes/no, names, dates).</li><li><strong>Reference: </strong><a href="https://aclanthology.org/D16-1264/"><em>SQuAD: 100,000+ Questions for Machine Comprehension of Text</em>.</a></li></ul><h4>10. Cosine Similarity</h4><ul><li><strong>Purpose</strong>: Evaluates the semantic similarity between two text embeddings by measuring the cosine of the angle between them.</li><li><strong>Application</strong>: Used in retrieval-augmented generation (RAG), semantic search, and clustering tasks to assess how closely related two pieces of text are.</li><li><strong>Reference</strong>: <a href="https://web.stanford.edu/class/cs124/lec/text_similarity.pdf">Text Similarity Algorithms: Cosine Similarity (Stanford NLP)</a></li></ul><h3>Conclusion</h3><p>Selecting appropriate evaluation metrics is crucial for assessing LLM performance effectively. The choice of metrics should align with the specific application and desired outcomes. Combining multiple metrics often provides a more comprehensive evaluation.</p><p>For further reading and detailed methodologies, refer to the provided references listed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f4eb19f159" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL vs PySpark: Performance Comparison in Databricks]]></title>
            <link>https://sammcruz.medium.com/sql-vs-pyspark-performance-comparison-in-databricks-216f5040e052?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/216f5040e052</guid>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 10:02:54 GMT</pubDate>
            <atom:updated>2025-03-13T10:02:54.880Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to spend hours debugging slow-running Spark jobs, scrolling through thousands of lines of logs, trying to pinpoint performance bottlenecks in data pipelines. When working with massive datasets, even simple transformations could drag down execution times, making it frustrating to optimize queries efficiently. Besides time to execute, we also have increase in costs, what every company want to avoid. Over time, I realized that <strong>choosing between Spark SQL and PySpark for different operations can make a huge difference</strong> in performance. In this article, I’ll break down a real comparison between <strong>string transformations, aggregations, and joins</strong>, showing when PySpark outperforms Spark SQL and why. Let’s get to it!</p><h3>Setup: Creating Sample Data</h3><p>Before we start comparing performance, let’s create a sample DataFrame with 10 million rows. This dataset will be used for various operations.</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col, rand, expr<br>import time<br>​<br># Create Spark session<br>spark = SparkSession.builder.appName(&quot;SQL_vs_PySpark&quot;).getOrCreate()<br>​<br># Generate a DataFrame with random data<br>df = (spark.range(0, 10_000_000)<br>      .withColumn(&quot;value&quot;, (rand() * 100).cast(&quot;int&quot;))<br>      .withColumn(&quot;text&quot;, expr(&quot;concat(&#39;sample_&#39;, id % 100)&quot;)))<br>​<br># Register as a temporary table for SQL queries<br>df.createOrReplaceTempView(&quot;test_table&quot;)</pre><h3>Test 1: String Manipulation — UPPERCASE Transformation</h3><p>Now that we have a test dataset, let’s proceed to the first test: string transformations.</p><p>String transformations are a common operation in ETL pipelines. Here, we compare UPPER(text_column) in Spark SQL vs. upper(col(&quot;text_column&quot;)) in PySpark. Although the result is the same, execution time may vary.</p><pre>#Spark SQL Approach<br>​<br>start_time = time.time()<br>​<br>df_sql = spark.sql(&quot;SELECT id, UPPER(text) AS text_upper FROM test_table&quot;)<br>df_sql.count()  # Force execution<br>​<br>sql_time = time.time() - start_time<br>print(f&quot;SQL UPPER Execution Time: {sql_time:.2f} seconds&quot;)<br>​<br># Using PySpark DataFrame API Approach:<br>​<br>from pyspark.sql.functions import upper<br>​<br>start_time = time.time()<br>​<br>df_pyspark = df.withColumn(&quot;text_upper&quot;, upper(col(&quot;text&quot;)))<br>df_pyspark.count()  # Force execution<br>​<br>pyspark_time = time.time() - start_time<br>print(f&quot;PySpark UPPER Execution Time: {pyspark_time:.2f} seconds&quot;)</pre><h3>Test 2: Aggregation — Sum of a Column</h3><p>Aggregating data is one of the most frequent operations in analytics and ETL pipelines. Let’s compare the performance of calculating the SUM of a numeric column using Spark SQL vs. PySpark.</p><pre>#Spark SQL Approach<br>​<br>start_time = time.time()<br>​<br>df_sql_agg = spark.sql(&quot;SELECT SUM(value) FROM test_table&quot;)<br>df_sql_agg.show()<br>​<br>sql_agg_time = time.time() - start_time<br>print(f&quot;SQL SUM Execution Time: {sql_agg_time:.2f} seconds&quot;)<br>​<br># Using PySpark DataFrame API Approach:<br>​<br>from pyspark.sql.functions import sum as spark_sum<br>​<br>start_time = time.time()<br>​<br>df_pyspark_agg = df.agg(spark_sum(&quot;value&quot;))<br>df_pyspark_agg.show()<br>​<br>pyspark_agg_time = time.time() - start_time<br>print(f&quot;PySpark SUM Execution Time: {pyspark_agg_time:.2f} seconds&quot;)</pre><h3>Test 3: Joins — SQL vs. PySpark</h3><p>Joining large datasets is one of the most computationally expensive operations in distributed computing. To test performance, let’s create a second dataset and perform an inner join.</p><pre># Let&#39;s first create a second dataset<br>df2 = (spark.range(0, 10_000_000)<br>       .withColumn(&quot;category&quot;, expr(&quot;id % 100&quot;))<br>       .withColumn(&quot;description&quot;, expr(&quot;concat(&#39;category_&#39;, id % 100)&quot;)))<br>​<br>df2.createOrReplaceTempView(&quot;category_table&quot;)<br><br>#Spark SQL Approach​<br>start_time = time.time()​<br>df_sql_join = spark.sql(&quot;&quot;&quot;<br>    SELECT t.id, t.value, c.description<br>    FROM test_table t<br>    INNER JOIN category_table c<br>    ON t.id = c.id<br>&quot;&quot;&quot;)<br>df_sql_join.count()  # Force execution<br>​<br>sql_join_time = time.time() - start_time<br>print(f&quot;SQL JOIN Execution Time: {sql_join_time:.2f} seconds&quot;)<br>​<br># Using PySpark DataFrame API Approach:​<br>start_time = time.time()​<br>df_pyspark_join = df.join(df2, on=&quot;id&quot;, how=&quot;inner&quot;)<br>df_pyspark_join.count()  # Force execution<br>​<br>pyspark_join_time = time.time() - start_time</pre><h3>Test 4: Row Number Window Function (SQL vs. PySpark)</h3><p>The final test will be a more complex transformation. <strong>Window functions</strong> are used when we need to perform calculations across a set of table rows related to the current row. <strong>Spark SQL handles window functions more efficiently than PySpark.</strong></p><pre>from pyspark.sql.window import Window<br>from pyspark.sql.functions import row_number, expr<br>​<br># Create a larger dataset<br>df_large = (<br>    spark.range(0, 50_000_000)  # 50 million rows<br>    .withColumn(&quot;category&quot;, expr(&quot;id % 1000&quot;))  # 1000 unique categories<br>    .withColumn(&quot;value&quot;, expr(&quot;rand() * 100&quot;))<br>)<br>​<br># Register as a SQL table<br>df_large.createOrReplaceTempView(&quot;large_table&quot;)<br>​<br>​<br># Spark SQL​<br>start_time = time.time()<br>​<br>df_sql_window = spark.sql(&quot;&quot;&quot;<br>    SELECT category, id, value, <br>           ROW_NUMBER() OVER (PARTITION BY category ORDER BY value DESC) AS row_num<br>    FROM large_table<br>&quot;&quot;&quot;)<br>df_sql_window.count()  # Force execution<br>​<br>sql_window_time = time.time() - start_time<br>print(f&quot;Spark SQL ROW_NUMBER Execution Time: {sql_window_time:.2f} seconds&quot;)<br>​<br># Pyspark​<br>start_time = time.time()<br>​<br>window_spec = Window.partitionBy(&quot;category&quot;).orderBy(df_large[&quot;value&quot;].desc())<br>​<br>df_pyspark_window = df_large.withColumn(&quot;row_num&quot;, row_number().over(window_spec))<br>df_pyspark_window.count()  # Force execution<br>​<br>pyspark_window_time = time.time() - start_time<br>print(f&quot;PySpark ROW_NUMBER Execution Time: {pyspark_window_time:.2f} seconds&quot;)</pre><h3>Conclusion: When to Use Spark SQL vs. PySpark</h3><p>Based on the results (see below), PySpark outperforms Spark SQL in string manipulations, aggregations, and joins, while Spark SQL is significantly faster for window functions (ROW_NUMBER()).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhBt4VMsuSlegMtwLAQB-Q.png" /><figcaption>Execution output</figcaption></figure><p><strong>String Manipulations (</strong>UPPER()<strong>) &amp; Aggregations</strong> (SUM()) → PySpark is faster</p><ul><li>PySpark directly executes transformations using the <strong>Catalyst optimizer</strong>, avoiding the extra overhead of SQL query parsing and execution plan generation.</li><li>Spark SQL introduces an additional <strong>query translation step</strong>, making it slightly slower for simple operations.</li></ul><p><strong>Joins </strong>(INNER JOIN) → PySpark is significantly faster</p><ul><li>PySpark’s .join() leverages the Tungsten execution engine, handling shuffling and partitioning more efficiently.</li><li>Spark SQL may choose a suboptimal join strategy, increasing execution time when statistics aren’t optimized.</li></ul><p><strong>Window Functions</strong> (ROW_NUMBER()) → Spark SQL is much faster</p><ul><li>Spark SQL optimizes window functions with Catalyst and executes them natively on the JVM, reducing shuffle overhead.</li><li>PySpark’s .withColumn(row_number().over(Window)) introduces Python-JVM serialization overhead, making it slower.</li></ul><h3>Final Recommendation:</h3><ul><li>✅ Use PySpark for simple transformations, aggregations, and joins, as it avoids SQL parsing overhead.</li><li>✅ Use Spark SQL for window functions and complex analytics, where query optimization plays a major role.</li><li>✅ Consider query readability — Spark SQL is often preferable when working with SQL-savvy teams.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=216f5040e052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Stage AI Systems with Databricks]]></title>
            <link>https://sammcruz.medium.com/building-multi-stage-ai-systems-with-databricks-e3170190f39c?source=rss-7d58fbcc818c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3170190f39c</guid>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Samantha Cruz]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 10:29:12 GMT</pubDate>
            <atom:updated>2025-02-25T10:29:12.172Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>AI systems have evolved from simple single-task models to multi-stage architectures that enhance reasoning, search, and execution. In this article, we’ll explore how to design multi-stage AI pipelines using Databricks, LLMs, and vector search, following an efficient workflow that allows for modularity, scalability, and better context-awareness.</p><p>We’ll break down the architecture into stages and provide simple code snippets to illustrate key concepts.</p><h3>Why Multi-Stage AI Systems?</h3><p>When building AI-powered applications, handling complex queries often requires multiple stages, including:</p><ol><li>Search &amp; Retrieval: Finding relevant documents from a large dataset.</li><li>Summarization &amp; Augmentation: Refining retrieved content for improved processing.</li><li>Contextualization: Structuring and prioritizing results.</li><li>Final Response Generation: Using LLMs to produce a coherent, final response.</li></ol><p>By structuring AI workflows in stages, we create a more robust, scalable, and interpretable system.</p><h3>Building a Multi-Stage AI System in Databricks</h3><h3>Step 1: Search and Retrieve Relevant Documents</h3><p>The first step in our pipeline is retrieving relevant data. We use Databricks Vector Search to find similar documents based on embeddings.</p><pre>from databricks.vector_search import VectorSearchClient</pre><pre>def run_search(query_text: str):<br>    client = VectorSearchClient()<br>    index = client.get_index(&quot;my_vector_index&quot;)<br>    results = index.similarity_search(query_text, num_results=5)<br>    return results</pre><pre># Example usage<br>query = &quot;What are the best practices for AI governance?&quot;<br>retrieved_docs = run_search(query)<br>print(retrieved_docs)</pre><p>This function retrieves the top 5 most relevant documents based on semantic similarity.</p><h3>Step 2: Summarizing Retrieved Documents</h3><p>Once we have relevant documents, we can summarize them to extract the most important information.</p><pre>from mlflow.deployments import get_deploy_client</pre><pre>def run_summary(content: str):<br>    client = get_deploy_client(&quot;databricks&quot;)<br>    response = client.predict(endpoint_name=&quot;summary_llm&quot;, inputs={&quot;content&quot;: content})<br>    return response[&quot;summary&quot;]</pre><pre># Example usage<br>summary = run_summary(retrieved_docs[0])<br>print(summary)</pre><p>By summarizing documents, we ensure only the most relevant details are passed to the next stage.</p><h3>Step 3: Structuring Context for Better Answers</h3><p>The next step is to organize the retrieved and summarized content into a structured format that can be effectively used in a QA model.</p><pre>def run_get_context(summaries: list):<br>    sorted_summaries = sorted(summaries, key=lambda x: x[&quot;relevanceScore&quot;], reverse=True)<br>    return &quot;\n&quot;.join([s[&quot;summary&quot;] for s in sorted_summaries[:3]])</pre><pre># Example usage<br>context = run_get_context([summary])<br>print(context)</pre><p>This function sorts summaries based on relevance and concatenates the top results into a single context.</p><h3>Step 4: Generating the Final Response with an LLM</h3><p>Finally, we use an LLM chat model to generate a well-structured response based on our curated context.</p><pre>def run_qa(question: str, context: str):<br>    client = get_deploy_client(&quot;databricks&quot;)<br>    response = client.predict(endpoint_name=&quot;qa_llm&quot;, inputs={&quot;question&quot;: question, &quot;context&quot;: context})<br>    return response[&quot;answer&quot;]</pre><pre># Example usage<br>final_answer = run_qa(query, context)<br>print(final_answer)</pre><p>The QA model now has the most relevant context to generate a high-quality response.</p><h3>Bringing Everything Together</h3><p>Now, let’s integrate all these stages into a single orchestrated workflow.</p><pre>def main_pipeline(question: str):<br>    search_results = run_search(question)<br>    summaries = [run_summary(doc) for doc in search_results]<br>    context = run_get_context(summaries)<br>    final_answer = run_qa(question, context)<br>    return final_answer</pre><pre># Example usage<br>response = main_pipeline(&quot;How can AI models be optimized for performance?&quot;)<br>print(response)</pre><p>By combining these modular functions, we create an efficient AI system that: <br>✅ Searches for relevant documents <br>✅ Summarizes key points <br>✅ Structures the most important information <br>✅ Generates an optimized answer</p><h3>Why Use Databricks for Multi-Stage AI?</h3><p>Databricks provides an ideal environment for deploying and scaling multi-stage AI systems:</p><ul><li>Databricks Vector Search: Enables efficient semantic search.</li><li>MLflow Integration: Deploy and manage LLMs easily.</li><li>Parallel Processing: Scale AI workloads efficiently.</li><li>Multi-Endpoint Architecture: Deploy different AI stages as independent services.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3170190f39c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>