<?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 Zach Jacobson on Medium]]></title>
        <description><![CDATA[Stories by Zach Jacobson on Medium]]></description>
        <link>https://medium.com/@jacobsonzach23?source=rss-48d59ab91f84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_bc0IprsBdShIhf2.jpg</url>
            <title>Stories by Zach Jacobson on Medium</title>
            <link>https://medium.com/@jacobsonzach23?source=rss-48d59ab91f84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:12:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacobsonzach23/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[The Best of Databricks, Loaded Straight to your Power BI Models]]></title>
            <link>https://medium.com/databrick-solutions-architect-blogs/the-best-of-databricks-loaded-straight-to-your-power-bi-models-7c271cd464ea?source=rss-48d59ab91f84------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c271cd464ea</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[dbsql]]></category>
            <category><![CDATA[data-ware-housing]]></category>
            <dc:creator><![CDATA[Zach Jacobson]]></dc:creator>
            <pubDate>Fri, 23 May 2025 13:55:55 GMT</pubDate>
            <atom:updated>2025-05-23T13:55:55.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authors</h3><p><a href="https://www.linkedin.com/in/zach-jacobson-4b6903100/">Zach Jacobson</a>, Solutions Architect @ Databricks<br><a href="https://www.linkedin.com/in/iamhobbs/">Hobbs</a>, Senior Solutions Architect @ Databricks</p><p>There are few more powerful partnerships than Power BI and Databricks; the world’s leading Lakehouse driving the world’s best BI tool. Over the past few years, both tools (and their respective companies) have worked on tight, seamless integrations allowing users to maintain data integrity while efficiently visualizing their data. This blog explores how to best make use of those integrations to serve the business in Power BI while keeping essential features like metadata, primary and foreign keys, and user-level queries intact in your Lakehouse.</p><h3>Overview of the Integration</h3><p>If you’re reading this, you probably already know both Databricks and Power BI, but to cover all our bases, let’s do a quick overview. Databricks is the world’s first and (arguably) best Lakehouse, a term which refers to a combination of a Data Warehouse and a Datalake. Leave it to the nerds to use essentially a pun to name their produce. A lakehouse allows organizations to process and analyze big data seamlessly regardless of format; audio, video, tabular, whatever. Thanks to Databricks unified governance layer, Unity Catalog, a user can publish directly from Databricks to Power BI. Our focus in this blog will be the Warehouse side of the Lakehouse.</p><p>Power BI (PBI) needs little introduction; it’s the most widely used BI tool in the world with more than five million subscribers. Its dashboarding functionality is the gold standard for most organizations, and you’d be hard-pressed to throw a stone in any given business and not a PBI report. With their relentless focus on business users, they’be made a tool that enables anyone to understand and analyze their data. Is this blog, we’re focused on a back-end piece of the Power BI suite called Semantic Models.</p><p>Alright, let’s dive in. Here are 5 key benefits of combining Databricks and Power BI.</p><h3>1. Seamlessly Surface Warehouse Metadata in Power BI</h3><p>Maintaining metadata is crucial for data integrity and readability. Having descriptions of your tables and columns helps users understand the context and meaning of the data they are analyzing and it bridges the gap from your technical data-engineer type folks down to business people. Frankly though, it’s sort of a pain to keep up with and, once it’s created, it’s hard to surface that knowledge in your reporting layer without additional tooling.</p><p>Through the integration of Databricks Unity Catalog and Power BI, users can now effortlessly pass Data Warehouse column descriptions and table comments directly into the semantic models. When publishing datasets from Databricks, this metadata travels with the data, ensuring that Power BI users view not only the data values but also the information that defines them.</p><p>Let’s walk through the steps</p><p>First up you need to add comments to your tables and column. Fortunately, Databricks makes getting started dead easy. From Databricks, open your table in Unity Catalog. If you Click the ‘AI Generate’ button over the top of your columns, a fine-tuned LLM will propose table and column descriptions for you, which you can then edit and approve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FuuXI9bIxEPc4EN2" /></figure><p><strong>PRO TIP: </strong>You don’t want to blindly accept the suggestions. The AI is designed to get you started but it’s always going to take someone with business knowledge to go through and ensure those results line up with your specific businesses understands those tables/fields.</p><p>Here’s what the suggestions can look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*9vTKUZVGcisQdXrG" /></figure><p>Once you’ve saved your metadata in the Databricks table, using the ‘Publish to Power BI Workspace’ button will pass all that data across to Power BI as table/column descriptions.</p><p>Here’s an example of a Databricks column commenting showing up for a Power BI report builder, starting on the Databricks side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7BLFSsnhOEcVnCM5" /></figure><p>And then again on the Power BI side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ZKWat7CC49-nB0h" /></figure><p>And here’s a table description in Databricks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*waa93skYKO67La5l" /></figure><p>And again in Power BI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pT76ggfEgZsTjZQu" /></figure><p><strong>PRO TIP: </strong>Once this metadata is published, if you want to change it you’re going to need to use the XMLA endpoints to edit those column/table descriptions, using a tool like Tabular Editor. So it pays to make sure you’re done with that documentation/commenting before you publish to Power BI as a semantic model.</p><h3>2. Automatic Relationship Logic</h3><p>In relational databases, primary and foreign keys are essential for establishing relationships between tables. An incorrect join can ruin your measures and calculations, destroying an otherwise perfectly functional logical model. Databricks maintains these key relationships when publishing to Power BI. By using Databricks primary and foreign key constraints in conjunction with the ‘Publish to Power BI Workspace’ functionality, you can ensure your tables are joined correctly every time. users can trust that their Power BI reports reflect accurate relational structures. Below, notice within Databricks Unity Catalog, PK and FK constraints are defined. Each column/table comment, PK, and FK will be inherited directly into Power BI semantic model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mATV8368eKt0T3v-" /></figure><p><strong>PRO TIP: </strong>Power BI is quite picky in what kind of relationships it will accept. The default behaviour will be to keep a single active relationship between tables that’s one-to-many and single directional. You also can’t join on multiple columns in the same join, so you may need to create natural keys before you define your constraints. If you want to change any of these relationships, use something like Tabular Editor.</p><h3>3. Publish to PBI w/ Hybrid mode: Direct Query and Import Mode</h3><p>One of the integration’s standout features is the ability to use both Direct Query and Import mode when connecting Power BI to Databricks SQL Warehouse. In Direct Query mode, Power BI retrieves data in real time, making it suitable for scenarios where fresh data is critical. Alternatively, Import mode allows for higher performance by caching data within Power BI, provided it is below certain sizes.</p><p><strong>PRO TIP:</strong> Composite models allow you to publish data stored in multiple types. You can apply some of this approach by selecting ‘Use dual storage mode’ in the second screenshot below. All other checkboxes left unchecked will be in Direct Query mode.</p><p>This flexibility empowers users to select the best approach based on their specific reporting requirements. By supporting both modes, organizations can strike a balance between performance and accuracy, aligning their analytics strategies with business needs.</p><p>Below are two screenshots of how you publish data from Unity Catalog directly into Power BI. There are only two steps, its that easy!</p><p>Step 1: Select the ‘Use with BI tools’ button and click ‘Publish to Power BI workspace’. This will bring up screenshot 2 below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*IyhiVfyFsRMtDh-r" /></figure><p>Step 2: Select your Power BI workspace and what tables to publish. Utilize the ‘Dual storage mode’ here if hybrid direct query and import mode is desired</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XFsEVY8wF5fJt1Gl" /></figure><p>Step 3: That is it. Below is the published semantic model in Power BI ready to be consumed. It contains all PK, FK, and meta data that was added within Databricks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bI4r9XlQ5MWHhbHy" /></figure><h3>4. Refresh Power BI Semantic Model from Databricks Workflows</h3><p>With the direct publishing capabilities, users can configure Power BI to refresh its semantic model based on workflows in Databricks. This feature is essential for maintaining up-to-date reports and dashboards without requiring manual intervention. Users can schedule refreshes or trigger them automatically through Databricks workflows, ensuring that reports in Power BI always reflect the latest data. This level of automation streamlines the reporting process and enhances the overall efficiency of data-driven decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCHHvYUb6kAE_mc4" /></figure><h3>5. See User Level Queries for Power BI Reports</h3><p>Understanding user engagement with reports can provide valuable insights into how data is utilized across the organization. The integration allows administrators to monitor user-level queries in Power BI reports that connect to Databricks. This tracking capability enables teams to identify popular reports, assess user behaviors, and make informed choices about future data modeling and reporting efforts. By gaining this visibility, organizations can optimize their data strategies and ensure that they are delivering the insights that matter most to their users.</p><p><strong>PRO TIP: </strong>You’ll only be able to see user-level queries in DirectQuery mode. Once your semantic model is published, you’ll have the option in the Power BI Service to either authenticate as the report builder or the report builder. Turning on SSO sign-on for the viewer will pass the users identity across, which not only lets you track their usage here but also apply Databricks RLS and OLS directly to the user without needing to duplicate those policies in the Power BI Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZvnBm2bq6iFyRXtA" /></figure><h3>Conclusion</h3><p>The direct publishing capabilities from Databricks to Power BI create a robust framework for businesses to leverage their data effectively while maintaining integrity. Retaining metadata, enforcing primary and foreign keys, and allowing for flexible querying modes are just a few of the features that enhance user experience and trust in data. By refreshing Power BI models through Databricks workflows and providing user-level visibility, organizations can ensure they remain agile in an ever-evolving data landscape.</p><p>As businesses continue to embrace data as a strategic asset, leveraging the partnership between Databricks and Power BI will undoubtedly drive improved insights and empowered decision-making across the organization. For further details on this integration, explore the official Databricks announcement<a href="https://www.databricks.com/blog/announcing-general-availability-publish-microsoft-power-bi-service-unity-catalog"> here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c271cd464ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/databrick-solutions-architect-blogs/the-best-of-databricks-loaded-straight-to-your-power-bi-models-7c271cd464ea">The Best of Databricks, Loaded Straight to your Power BI Models</a> was originally published in <a href="https://medium.com/databrick-solutions-architect-blogs">Databrick Solutions Architect Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Electrical Fault Detection: The Power of Databricks and MATLAB]]></title>
            <link>https://medium.com/databrick-solutions-architect-blogs/transforming-electrical-fault-detection-the-power-of-databricks-and-matlab-0aff9f2ab7bf?source=rss-48d59ab91f84------2</link>
            <guid isPermaLink="false">https://medium.com/p/0aff9f2ab7bf</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[matlab]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[simulink]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Zach Jacobson]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 15:25:02 GMT</pubDate>
            <atom:updated>2024-10-09T19:00:12.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJzMX6CoJOmS8Kee13oYhQ.png" /></figure><h3>Introduction</h3><p>If you are in the Tech industry, chances are you have either heard of Databricks, MATLAB, or both perhaps. If you haven’t, give it a quick google search and you will find out very quickly.</p><p>But today, we come here to talk about a bigger challenge that many utility companies and anyone that consumes electricity deals with every day… Power outages. My favorite is when you wake up or just about to go to bed and all the lights shut off. You immediately get on your phone and check to see if others are experiencing an outage and it turns out it’s your whole neighborhood! Now it’s a race against the clock for utility companies to identify what caused the outage and locate where it occurred. Most likely you will be without power for 3–4 hours if you are lucky.</p><p>What if I told you, that your utility company could drastically reduce the time it takes to identify the location and type of fault that occurs during an outage? Every day utility companies spend wasted man-hours locating and inspecting for damage/unsafe conditions caused by electrical faults. With Databricks and MATLAB together, we are about to change the utility industry standard! Buckle up, I am about to explain how that could be possible very soon.</p><h3>MATLAB<strong> and Databricks Integration</strong></h3><p>To start off the work completed on MATLAB will require the following licenses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvWwgGNFV4yZmZ7NXjXJ8Q.png" /></figure><h4>MATLAB Model Development</h4><p>The simulation model developed in MATLAB follows the IEEE 123 fault standard. The input of the model includes variation of logarithmic resistance values over a constant time period. The output includes the following details:</p><ul><li>A total of 554 fault sequences within the system</li><li>55 seconds for each simulation. Equating to 10 faults/second</li><li>70 of the fault sequences are three-phase buses, with 7 fault sequences possible per bus (70*7 = 490 total faults for 3-phase buses)</li><li>9 of the fault sequences are for two-phase buses, with 3 fault sequences possible per bus (9*3 = 27 total faults for 2-phase buses)</li><li>55 of the fault sequences are for one-phase buses, with 1 fault sequences per bus (55 * 1 = 55 total faults for 1-phase buses)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*6jNdVJ0CHREViCxl" /><figcaption>Magenta dot = subtation, all other dots are faults and location</figcaption></figure><p>The awesome thing here is you can continue to develop your favorite algorithms on MATLAB, compile the code into a python wheel file and seamlessly deploy MATLAB runtime and algorithms on a Databricks cluster</p><h4>Deploy MATLAB Model on Databricks</h4><p>Once the model is developed you can deploy onto Databricks in several different ways (FUTURE LINK COMING) but today I will be focusing on how to deploy compiled MATLAB models and functions as libraries on a Databricks cluster.</p><p>Using <a href="https://www.mathworks.com/solutions/partners/databricks.html#"><strong>this</strong></a> Matlab interface for Databricks, makes the Matlab and integration seamless. For further in depth instructions on how to set this up can be set here: <a href="https://github.com/zjacobson1016/matlab_dbr_deploy/blob/main/INSTALL%20STEPS_%20Matlab.md"><strong>INSTRUCTIONS LINK</strong></a>. Below is the workflow that was automatically deployed from MATLAB SDK and API. The end results is a shell script that is attached to your Databricks cluster and builds MATLAB and Simulink runtime upon launching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QIKbPtC5boJMtsLF" /></figure><h4>Create Databricks Cluster w/ MATLAB Runtime</h4><p>Once you have built out the Databricks cluster with MATLAB and Simulink runtime installed, it’s now time to launch the cluster. Once the cluster is launched we then need to choose the most optimal cluster size for our simulation. I conducted 3 separate experiments, each creating 10 simulations. See below (Cluster Config Comparison) for best price/performance on Databricks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EydvFdKTGqS52NGc" /></figure><p><strong>KEEP IN MIND:</strong> I tried running this specific simulation on my local machine and it took ~13 hours. Scaling this to less than 1 hour on Databricks is a huge benefit!</p><p><strong>Cluster Config Comparison (10 simulations) :</strong></p><ul><li>Driver and worker type: r6id.xlarge, 32 GB memory, 4 cores, 4 worker nodes, Photon and autoscaling enabled <strong>(Option 1)</strong></li><li>Driver and worker type: r5dn.2xlarge, 64 GB memory, 8 cores, 4 workers, Photon and autoscaling enbaled <strong>(Option 2)</strong></li><li>Driver and worker type: r5dn.2xlarge, 128 GB memory, 16 cores, 4 workers, Photon and autoscaling enbaled <strong>(Option 3)</strong></li></ul><p>The first compute instance above runs for about 3.5 hours, the second instance above runs for ~45 minutes and the third instance above runs for ~45 minutes. Therefore, Option 2 was the most optimal for our simulation as increasing cluster size had diminished marginal returns.</p><h4>Run Simulation on Databricks</h4><p>Now that you have created and launched your cluster, it’s time to run the simulation on Databricks! See below for a screen shot of a Databricks notebook and the imported libraries and functions deployed from MATLAB. Notice the naming conventions below that might look familiar (mapInPandas, applyInPandas,ect…) . Each of the functions imported are allowing the MATLAB simulation/model to be executed in a Spark parallelized fashion.</p><p>As you can see we add random resistance inputs into the PySpark data frame for our simulation. Once the data frame is created, we use the “applyInPandas” function to execute the MATLAB and Simulink model via the libaries imported in cell 3 below. The libraries are made available via a <a href="https://docs.databricks.com/en/jobs/how-to/use-python-wheels-in-workflows.html#:~:text=September%2020%2C%202024,code%20in%20your%20Databricks%20jobs."><strong>wheel</strong></a> file that was created and deployed via the <strong>INSTRUCTIONS LINK </strong>above. The model will simulate a data set that will allow us to train our CNN model later in this blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mv2rnb8R-xJ-m4il" /><figcaption>MATLAB Library Imports</figcaption></figure><h4>Interact with Output</h4><p>After the model has simulated the data and distributed the compute using Spark on Databricks, it is then written to a Delta table in Unity Catalog. Now we can interact with the data and share across our workspace with the appropriate permissions. See three snippets of the output below.</p><p>The first snippet (far left) shows the schema of the MATLAB model output. The second snippeet (middle) shows the output target variable which is what we will try and predict in the succeeding steps. The target variable “fault_class” is describing what type of fault occurs when the following features are measured. The third snippet (far right) is the location (X_coord,Y_coord) where the fault occurred based from the substation (0,0) coordinate. You can use the distance formula to calculate the exact fault location in feet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*G7TSIZdquP3XD5CF" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*HmlLzSVEJJQRKfK9" /></figure><h4>Train CNN Model on Output</h4><p>A significant challenge facing utility companies today is transitioning from reactive to proactive detection of potential electrical faults. Moreover, once a prediction indicates a high likelihood of a fault, the next hurdle is accurately identifying the precise location within the electrical grid where the fault may occur. To effectively train models for this purpose, utility companies require a substantial amount of labeled data to develop fault detection algorithms. This is where our innovative approach comes into play: by leveraging MATLAB and Databricks, we utilize physical models to create powerful simulations that generate the necessary data for training machine learning models. In this context, we implemented a Convolutional Neural Network (CNN) model to enhance our predictive capabilities and improve the reliability of electrical systems.</p><p>Convolutional Neural Networks (CNNs) are particularly effective at detecting electrical faults due to their ability to automatically learn and extract relevant features from complex data sets, especially specific to the use case that use time-series signals from electrical systems. These networks utilize convolutional layers that identify patterns and anomalies by applying filters across the input data, enabling them to recognize subtle changes indicative of faults.</p><p>For instance, when analyzing waveforms of electrical components, CNNs can discern deviations from normal behavior, such as overheating or unusual current patterns. Additionally, their hierarchical structure allows CNNs to learn from varying levels of abstraction, making them well-suited for diagnosing a range of electrical issues, enhancing predictive maintenance, and reducing downtime in industrial applications. Overall, their robustness and accuracy in pattern recognition make CNNs a valuable tool in the proactive management of electrical systems.</p><h3>Conclusion</h3><p>In conclusion, the integration of MATLAB and Databricks offers a streamlined approach to simulation and model development, significantly enhancing the capabilities of utility companies in detecting electrical faults. By harnessing Databricks’ computing power and Apache Spark’s scalability, organizations can efficiently scale their MATLAB simulations, achieving remarkable cost efficiency while processing large data sets. This is particularly crucial as many utility companies currently lack the labeled data necessary for training effective predictive models.</p><p>Through this combined technology platform, utility companies can overcome data limitations, improve their fault detection strategies, and ultimately enhance the reliability of their electrical systems, paving the way for a more proactive and resilient approach to managing electrical infrastructure.</p><p><strong>REFERENCES:</strong> Instructions Link again: <a href="https://github.com/zjacobson1016/matlab_dbr_deploy/blob/main/INSTALL%20STEPS_%20Matlab.md"><strong>INSTRUCTIONS LINK</strong></a><strong>. </strong>Currently I have published a working example at this <a href="https://github.com/zjacobson1016/matlab_dbr_deploy"><strong>Github Repo</strong></a>. I will be adding and polishing this over the next two months.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0aff9f2ab7bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/databrick-solutions-architect-blogs/transforming-electrical-fault-detection-the-power-of-databricks-and-matlab-0aff9f2ab7bf">Transforming Electrical Fault Detection: The Power of Databricks and MATLAB</a> was originally published in <a href="https://medium.com/databrick-solutions-architect-blogs">Databrick Solutions Architect Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Late Arriving Dimensions on Databricks]]></title>
            <link>https://medium.com/databrick-solutions-architect-blogs/how-to-handle-late-arriving-dimensions-on-databricks-677b29f569dc?source=rss-48d59ab91f84------2</link>
            <guid isPermaLink="false">https://medium.com/p/677b29f569dc</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <category><![CDATA[structured-streaming]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[late-arriving-dimension]]></category>
            <dc:creator><![CDATA[Zach Jacobson]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 14:01:52 GMT</pubDate>
            <atom:updated>2024-09-06T15:02:42.622Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The art of classic Data Warehousing is still relevant, even in today’s AI takeover. The same problem still exists, if you don’t have well structured and clean data, you don’t have AI and/or machine learning. Late arriving dimensions occur when a record arrives in the fact table but has not yet arrived in the dimension table. The most common reason for late arriving dimensions is due to different load times of each fact and dimension table. Kimball (God Father of Data Warehousing) has created a best practice on how to handle late arriving dimensions but today I will show you can do it on Databricks.</p><p><strong><em>Disclaimer: I give credit to the McGraw Hill team who wrote the original article </em></strong><a href="https://www.databricks.com/blog/2020/12/15/handling-late-arriving-dimensions-using-a-reconciliation-pattern.html"><strong><em>here</em></strong></a><strong><em>. Several things were modified throughout the conversion but the overall architecture is the same. (i.e. Using Python vs. Scala in the old blog and using Databricks Unity Catalog Volumes and Tables)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmW2BLxIiuS-F5hXJXNZBg.png" /><figcaption>Architectural Diagram</figcaption></figure><p><strong>Note: Each number label in the diagram above is directly tied to an individual step numbered below.</strong></p><p><strong>Let’s break down each piece from the diagram above!</strong></p><h3><strong>1. Create Delta Tables to set up the pipeline:</strong></h3><pre>#Create checkpoint in Unity Catalog Volumes. The checkpoint will remember what <br>#has and has not been proccessed<br><br>spark.sql(&#39;&#39;&#39;<br>CREATE VOLUME mfg_mid_central_sa.zach_jacobson.logins_checkpoint<br>&#39;&#39;&#39; <br>)</pre><pre><br>#Checkpoint/Unity Catalog Volumes path<br>logins_checkpoint = &quot;/Volumes/mfg_mid_central_sa/zach_jacobson/logins_checkpoint&quot;<br><br>#Max number of retries for data written in error table.<br>#You can have unlimited retries if you want and remove this variable<br>maxRetryAttempts = 3<br><br>#Update status in error table<br>STATUS_RESOLVED = &quot;RESOLVED&quot;<br>STATUS_NOT_RESOLVED = &quot;NOT_RESOLVED&quot;<br>STATUS_DEAD_LETTER = &quot;DEAD&quot;</pre><pre>#Target logins table<br>spark.sql(&#39;&#39;&#39;<br>  CREATE TABLE IF NOT EXISTS mfg_mid_central_sa.zach_jacobson.logins(<br>    user_id BigInt,<br>    timestamp Timestamp,<br>    date Date,<br>    first_name String,<br>    last_name String,<br>    login_count Int,<br>    audit_created_datetime Timestamp,<br>    audit_modified_datetime Timestamp<br>)<br>&#39;&#39;&#39;)<br><br>#Reconciliation Table<br>spark.sql(&#39;&#39;&#39;<br>  CREATE TABLE IF NOT EXISTS mfg_mid_central_sa.zach_jacobson.reconciliation(<br>    raw String,<br>    event_id String,<br>    pipeline_name String,<br>    status String,<br>    retry_count Int,<br>    error_created_datetime Timestamp,<br>    audit_created_datetime Timestamp,<br>    audit_modified_datetime Timestamp<br>  )<br>&#39;&#39;&#39;)</pre><h3><strong>2. Create dummy Dimension Table, Fact Table, and retry able data.</strong></h3><pre>#Dimension Table<br>import random<br>import string<br>#Function to generate next ID<br>def next_id():<br>    next_id.counter += 1<br>    return next_id.counter<br>next_id.counter = 0<br><br># Generate data<br>data = [<br>    (next_id(), &#39;&#39;.join(random.choices(string.ascii_letters + string.digits, k=10)), <br>    &#39;&#39;.join(random.choices(string.ascii_letters + string.digits, k=10)))<br>    for _ in range(200)<br>]<br><br># Create DataFrame<br>users_df = spark.createDataFrame(data, [&quot;user_id&quot;, &quot;first_name&quot;, &quot;last_name&quot;])<br><br># Write DataFrame to Delta table<br>users_df.write.format(&quot;delta&quot;) \<br>    .mode(&quot;overwrite&quot;) \<br>    .saveAsTable(&quot;mfg_mid_central_sa.zach_jacobson.users&quot;)<br><br># Read the Delta table<br>users_df = spark.read.format(&quot;delta&quot;).table(&quot;mfg_mid_central_sa.zach_jacobson.users&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*x3DUJ0S6Tr-fjYhjSmqdOQ.png" /></figure><pre>from pyspark.sql.functions import col, get_json_object, lit<br>#Read reconcile data that have status = &quot;NOT_RESOLVED&quot; and have not exausted number of retries. <br># Note that this data is updated via batch process that runs periodically.<br># As soon as new data is written to reconciliation table, it will be processed here. <br># Reading stream from the Delta table<br>retryable_data = spark.readStream \<br>    .format(&quot;delta&quot;) \<br>    .option(&quot;ignoreChanges&quot;, &quot;true&quot;) \<br>    .table(&quot;mfg_mid_central_sa.zach_jacobson.reconciliation&quot;) \<br>    .filter((col(&quot;status&quot;) == STATUS_NOT_RESOLVED) &amp; (col(&quot;retry_count&quot;) &lt;= maxRetryAttempts)) \<br>    .select(<br>        get_json_object(col(&quot;raw&quot;), &quot;$.user_id&quot;).alias(&quot;user_id&quot;),<br>        get_json_object(col(&quot;raw&quot;), &quot;$.event_id&quot;).alias(&quot;event_id&quot;),<br>        get_json_object(col(&quot;raw&quot;), &quot;$.timestamp&quot;).alias(&quot;timestamp&quot;),<br>        lit(True).alias(&quot;is_retry_event&quot;),<br>        col(&quot;pipeline_name&quot;)<br>    )</pre><pre>#Fact table creation<br>#We will generate synthetic login event to simulate a user_ids that are not<br>#in user table yet.<br>#We can treat such events as early arriving facts. <br># UNION this with retryable records<br><br>from pyspark.sql.functions import col, floor, lit, rand<br><br><br>#Read in data from checkpoint location pointed to Unity Catalog Volumes.<br>#This creates the fact table and then unions the events that were marked &quot;is_retry_event&quot;<br>logins_data = spark.readStream \<br>    .format(&quot;delta&quot;) \<br>    .option(&quot;checkpointLocation&quot;, logins_checkpoint) \<br>    .load() \<br>    .withColumnRenamed(&quot;value&quot;, &quot;event_id&quot;) \<br>    .withColumn(&quot;user_id&quot;, (floor(rand() * 1000) % 225) + 1) \<br>    .withColumn(&quot;is_retry_event&quot;, lit(False)) \<br>    .withColumn(&quot;pipeline_name&quot;, lit(&quot;logins-stream&quot;)) \<br>    .unionByName(retryable_data)</pre><figure><img alt="Fact table with retry events" src="https://cdn-images-1.medium.com/max/1024/1*LjFRx0oSENWoShMG4Xz4pg.png" /><figcaption>Fact Table w/ Retry Records</figcaption></figure><h3><strong>3. Join the fact table w/ retry records to the dimension (user) table</strong></h3><pre>#Join facts with users dimension <br>#Mark the record as &#39;retryable&#39; is corresponding dimension has not arrived yet.<br>from pyspark.sql.functions import to_date<br>joined_df = logins_data.join(users_df, on=&quot;user_id&quot;, how=&quot;left&quot;) \<br>    .withColumn(&quot;is_retryable&quot;, col(&quot;first_name&quot;).isNull() &amp; col(&quot;last_name&quot;).isNull()) \<br>    .withColumn(&quot;date&quot;, to_date(col(&quot;timestamp&quot;)))</pre><p>Notice below, the joined fact and dimension table with first_name and last_name rows marked “null”. These are considered late arriving dimensions. We will show these at the end of the walkthrough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXABtFuMiC-lZxbH9AUR5w.png" /><figcaption>Fact and Dimension Table joined</figcaption></figure><h3><strong>4. Retry and non-retry records. In this block, a foreachBatch function is created to separate for several things:</strong></h3><p><a href="https://docs.databricks.com/en/structured-streaming/foreach.html"><strong>(forEachbatch documentation link)</strong></a></p><p>a. Write the ouput of a streaming aggregation into a delta table via SQL MERGE INTO operation.</p><p>b. Separate the retry and non-retry records.</p><p>c. The retry records are written to an append only delta table named “streaming_pipeline_errors”.</p><p>d. The non-retry records are used to update the “logins” target table (Fact and dimensions with most updated data).</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col, struct, to_json, current_timestamp, when, expr, max as spark_max, count, first<br>from delta.tables import DeltaTable<br><br><br>def foreach_batch_function(ds, batch_id):<br>    # Part 1: Write retryable data OR update status of retry events to orchestration<br>    invalid_or_reconciled_records = ds.filter((col(&quot;is_retryable&quot;)) | (col(&quot;is_retry_event&quot;))) \<br>        .select(<br>            col(&quot;event_id&quot;),<br>            col(&quot;timestamp&quot;),<br>            to_json(struct(&quot;event_id&quot;, &quot;user_id&quot;, &quot;timestamp&quot;)).alias(&quot;raw&quot;),<br>            current_timestamp().alias(&quot;audit_created_datetime&quot;),<br>            col(&quot;pipeline_name&quot;),<br>            when(col(&quot;is_retryable&quot;), STATUS_NOT_RESOLVED).otherwise(STATUS_RESOLVED).alias(&quot;status&quot;)<br>        )<br>    invalid_or_reconciled_records.write \<br>        .format(&quot;delta&quot;) \<br>        .mode(&quot;append&quot;) \<br>        .saveAsTable(&quot;mfg_mid_central_sa.zach_jacobson.streaming_pipeline_errors&quot;)<br>    # Part 2: Write good data to delta table<br>    #Dedup on the MERGE keys<br>    good_data = ds.filter(~col(&quot;is_retryable&quot;)) \<br>        .drop(&quot;is_retryable&quot;, &quot;is_retry_event&quot;) \<br>        .groupBy(&quot;user_id&quot;, &quot;date&quot;) \<br>        .agg(<br>            spark_max(&quot;timestamp&quot;).alias(&quot;timestamp&quot;),<br>            count(&quot;*&quot;).alias(&quot;login_count&quot;),<br>            first(&quot;first_name&quot;).alias(&quot;first_name&quot;),<br>            first(&quot;last_name&quot;).alias(&quot;last_name&quot;)<br>        ) \<br>        .withColumn(&quot;audit_created_datetime&quot;, current_timestamp()) \<br>        .withColumn(&quot;audit_modified_datetime&quot;, current_timestamp())<br>    #Update the daily login count<br>    DeltaTable.forName(spark, &quot;mfg_mid_central_sa.zach_jacobson.logins&quot;).alias(&quot;t&quot;) \<br>        .merge(<br>            good_data.alias(&quot;u&quot;),<br>            &quot;u.user_id = t.user_id AND u.date = t.date&quot;<br>        ) \<br>        .whenMatchedUpdate(<br>            condition=&quot;t.timestamp &lt;= u.timestamp&quot;,<br>            set={<br>                &quot;login_count&quot;: &quot;t.login_count + 1&quot;,<br>                &quot;audit_modified_datetime&quot;: &quot;current_timestamp()&quot;<br>            }<br>        ) \<br>        .whenNotMatchedInsertAll() \<br>        .execute()<br># Read the stream and process it<br>joined_df \<br>.writeStream \<br>.trigger(availableNow=True) \<br>.option(&quot;checkpointLocation&quot;, logins_checkpoint) \<br>.foreachBatch(foreach_batch_function) \<br>.start() \<br>.awaitTermination()</pre><h3><strong>5. Next, a reconciliation job is created that runs as a batch job, periodically.</strong></h3><p>Note: The batch job takes the “streaming_pipeline_errors” table, dedups it, and writes it to a reconciliation table. The table is then injected back into the stream for reprocessing.</p><pre>from pyspark.sql.functions import col, coalesce, max, struct, current_timestamp, lit<br>from delta.tables import DeltaTable<br><br>def run_reconciliation():<br><br>    # Get the start datetime to query new records<br>    prev_max_datetime = spark.sql(&quot;&quot;&quot;<br>        SELECT COALESCE(MAX(error_created_datetime), &#39;1970-01-01T00:00:00.001+0000&#39;)<br>        FROM mfg_mid_central_sa.zach_jacobson.reconciliation<br>    &quot;&quot;&quot;).head()[0]<br><br>    # Get the new error events from streaming_pipeline_errors<br>    new_errors = (spark.read<br>                  .table(&quot;mfg_mid_central_sa.zach_jacobson.streaming_pipeline_errors&quot;)<br>                  .filter(col(&quot;audit_created_datetime&quot;) &gt; prev_max_datetime))<br><br>    # Deduplicate records<br>    new_errors = (new_errors.groupBy(&quot;pipeline_name&quot;, &quot;event_id&quot;)<br>                  .agg(max(struct(&quot;audit_created_datetime&quot;, &quot;event_id&quot;, &quot;pipeline_name&quot;, &quot;status&quot;, &quot;raw&quot;)).alias(&quot;latest&quot;))<br>                  .select(&quot;latest.*&quot;))<br><br>    # Set defaults for the merge<br>    new_errors = (new_errors<br>                  .withColumnRenamed(&quot;audit_created_datetime&quot;, &quot;error_created_datetime&quot;)<br>                  .withColumn(&quot;audit_created_datetime&quot;, current_timestamp())<br>                  .withColumn(&quot;audit_modified_datetime&quot;, current_timestamp())<br>                  .withColumn(&quot;retry_count&quot;, lit(0)))<br><br>    # This condition is used to update `status` during the MERGE<br>    max_retry_attempts = 3  # Adjust according to your configuration<br>    status_update_sql = f&quot;&quot;&quot;<br>        CASE WHEN u.status = &#39;{STATUS_NOT_RESOLVED}&#39; THEN<br>            CASE WHEN t.retry_count &gt;= {max_retry_attempts}<br>                THEN &#39;{STATUS_DEAD_LETTER}&#39; ELSE &#39;{STATUS_NOT_RESOLVED}&#39; END<br>        ELSE &#39;{STATUS_RESOLVED}&#39; END<br>    &quot;&quot;&quot;<br><br>    # Merge the new errors into the reconciliation table<br>    delta_table = DeltaTable.forName(spark, &quot;mfg_mid_central_sa.zach_jacobson.reconciliation&quot;)<br><br>    (delta_table.alias(&quot;t&quot;)<br>     .merge(new_errors.alias(&quot;u&quot;), &quot;u.pipeline_name = t.pipeline_name AND u.event_id = t.event_id&quot;)<br>     .whenMatchedUpdate(condition = &quot;t.error_created_datetime &lt;= u.error_created_datetime&quot;,<br>        set={&quot;status&quot;: status_update_sql,<br>         &quot;audit_modified_datetime&quot;: &quot;current_timestamp()&quot;,<br>         &quot;retry_count&quot;: f&quot;CASE WHEN u.status = &#39;{STATUS_RESOLVED}&#39; THEN -1 ELSE t.retry_count + 1 END&quot;})<br>     .whenNotMatchedInsertAll()<br>     .execute())<br><br>#run function<br>run_reconciliation()</pre><h3>6. <strong>Finally, we will rerun the pipeline to see how everything is processed.</strong></h3><p>Below we will inject data for user_id 218 and 217. (<strong>refer back to step 3</strong>, where I reference these user_id’s that are both null values at the time). Injecting this data, will show how a late arriving dimension is processed through out pipeline.</p><pre>from pyspark.sql import Row<br># Function to generate a random alphanumeric string of given length<br>def random_string(length):<br>    return &#39;&#39;.join(random.choices(string.ascii_letters + string.digits, k=length))<br><br># Now inject first and last names in dimension values for user_id 218 and 217 to process.<br>late_arriving_dims = [<br>    Row(218, random_string(10), random_string(10)),<br>    Row(217, random_string(10), random_string(10))<br>]<br><br># Create DataFrame<br>late_arriving_dims_df = spark.createDataFrame(late_arriving_dims, [&quot;user_id&quot;, &quot;first_name&quot;, &quot;last_name&quot;]) \<br>.write \<br>.format(&quot;delta&quot;) \<br>.mode(&quot;append&quot;) \<br>.saveAsTable(&quot;mfg_mid_central_sa.zach_jacobson.users&quot;)</pre><h3><strong>7. Rerun the following cells (Note: same cells from steps 2.5–5)</strong></h3><pre>from pyspark.sql.functions import col, get_json_object, lit<br>#Read reconcile data that have status = &quot;NOT_RESOLVED&quot; and have not exausted number of retries. <br># Note that this data is updated via batch process that runs periodically.<br># As soon as new data is written to reconciliation table, it will be processed here. <br># Reading stream from the Delta table<br>retryable_data = spark.readStream \<br>    .format(&quot;delta&quot;) \<br>    .option(&quot;ignoreChanges&quot;, &quot;true&quot;) \<br>    .table(&quot;mfg_mid_central_sa.zach_jacobson.reconciliation&quot;) \<br>    .filter((col(&quot;status&quot;) == STATUS_NOT_RESOLVED) &amp; (col(&quot;retry_count&quot;) &lt;= maxRetryAttempts)) \<br>    .select(<br>        get_json_object(col(&quot;raw&quot;), &quot;$.user_id&quot;).alias(&quot;user_id&quot;),<br>        get_json_object(col(&quot;raw&quot;), &quot;$.event_id&quot;).alias(&quot;event_id&quot;),<br>        get_json_object(col(&quot;raw&quot;), &quot;$.timestamp&quot;).alias(&quot;timestamp&quot;),<br>        lit(True).alias(&quot;is_retry_event&quot;),<br>        col(&quot;pipeline_name&quot;)<br>    )</pre><pre>#Fact table creation<br>#We will generate synthetic login event to simulate a user_ids that are not<br>#in user table yet.<br>#We can treat such events as early arriving facts. <br># UNION this with retryable records<br><br>from pyspark.sql.functions import col, floor, lit, rand<br><br>#Read in data from checkpoint location pointed to Unity Catalog Volumes.<br>#This creates the fact table and then unions the events that were marked &quot;is_retry_event&quot;<br>logins_data = spark.readStream \<br>    .format(&quot;delta&quot;) \<br>    .option(&quot;checkpointLocation&quot;, logins_checkpoint) \<br>    .load() \<br>    .withColumnRenamed(&quot;value&quot;, &quot;event_id&quot;) \<br>    .withColumn(&quot;user_id&quot;, (floor(rand() * 1000) % 225) + 1) \<br>    .withColumn(&quot;is_retry_event&quot;, lit(False)) \<br>    .withColumn(&quot;pipeline_name&quot;, lit(&quot;logins-stream&quot;)) \<br>    .unionByName(retryable_data)</pre><pre>#Join facts with users dimension <br>#Mark the record as &#39;retryable&#39; is corresponding dimension has not arrived yet.<br>from pyspark.sql.functions import to_date<br>joined_df = logins_data.join(users_df, on=&quot;user_id&quot;, how=&quot;left&quot;) \<br>    .withColumn(&quot;is_retryable&quot;, col(&quot;first_name&quot;).isNull() &amp; col(&quot;last_name&quot;).isNull()) \<br>    .withColumn(&quot;date&quot;, to_date(col(&quot;timestamp&quot;)))</pre><pre># Read the stream and process it<br>joined_df \<br>.writeStream \<br>.trigger(availableNow=True) \<br>.option(&quot;checkpointLocation&quot;, logins_checkpoint) \<br>.foreachBatch(foreach_batch_function) \<br>.start() \<br>.awaitTermination()<br><br>#run reconcile function<br>#run_reconciliation()</pre><h3>See the results from all Delta tables:</h3><p>Notice the “reconciliation” table first 3 rows that contain user_id 217 and 218. You can see the “status” column is now changed to resolved, since the late arriving dimension has “Arrived!” You can then see it was injected back into the pipeline processed and merged into the “logins” target table.</p><figure><img alt="Notice the first 3 rows that are referring to user_id 217 and 218. Follow these ids through the output examples below." src="https://cdn-images-1.medium.com/max/1024/1*l2CX3auAxeGdA_0x_n8f4g.png" /><figcaption>Reconciliation Table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyvCq6AgtWuwrMaeAQSe_Q.png" /></figure><h3>Conclusion</h3><p>Today you have seen how Databricks can handle late arriving dimensions using PySpark Structured Streaming language. Structured Streaming, which is built on top of Spark SQL engine, allows for batch and real time processing. The combination of batch and streaming capabilities all within PySpark, gives extreme flexibility for a developer when architecting classic Data Warehouse type workflows. PySpark Structured Streaming differs from classic SQL Data Warehouse workloads by allowing for scalability, real time data processing, and fault tolerant capabilities.</p><p>Stay tuned for an upcoming blog about Late Arriving Dimensions but using Databrick’s Delta Live Tables and Incremental Matertiazed Views. Feel free to reach out to me on <a href="http://www.linkedin.com/in/zach-jacobson-4b6903100">LinkedIn</a> or comment on the blog for questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=677b29f569dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/databrick-solutions-architect-blogs/how-to-handle-late-arriving-dimensions-on-databricks-677b29f569dc">How to Handle Late Arriving Dimensions on Databricks</a> was originally published in <a href="https://medium.com/databrick-solutions-architect-blogs">Databrick Solutions Architect Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>