zaterdag 5 december 2026

Databricks series : AI Project: Designing the entities for the Conceptual Data Model for a Mortgage AI Lab

Introduction

In the previous articles, I created a dedicated Unity Catalog catalog called "mortgage_ai_lab" and organized it into four schemas: Bronze, Silver, Gold and AI. 


Before loading the first datasets into Databricks, I want to take a step back and look at the business domain itself. The goal is to build a realistic mortgage data platform that will eventually support data engineering, analytics and AI-powered applications.  But before building pipelines or AI agents, we need to understand the information we are working with. This is where conceptual data modelling comes in.


In these (following) blogposts I'll describe the design of a Conceptual (Data) Model (CDM) . I attended the course "Business-oriented Data Modelling" by Alec Sharp in the Netherlands and I can recommend this course for a step by step approach on how to model Conceptual Data Models and Logical Data Models. So this blogpost is a tribute to Alec Sharp ;-). Thanks Alec!


We are building upon what we already have :


Introducing our hypothetical mortgage provider

For this project, we will assume that we are building a data platform for a hypothetical mortgage provider. The company offers mortgage products to both private individuals and businesses that want to finance residential or commercial properties.


As a mortgage provider, the company needs to manage more than just customers and mortgage contracts. A mortgage may involve multiple borrowers, consist of several loan parts, and be secured by one or more properties. Each loan part can have its own interest rate arrangements and repayment history.


The company therefore needs a data model that captures the relationships between customers, mortgages, loan parts, properties, interest rate periods, and payments.


Our hypothetical mortgage provider supports the following business scenarios:

  • Customers: A customer can be a private individual or an organization, such as a property investment company.

  • Mortgage agreements: A mortgage agreement can involve one or more customers, for example a couple purchasing a house together.

  • Loan parts: A mortgage can consist of multiple loan parts, each with its own principal amount, repayment structure, and interest rate arrangements.

  • Properties: A mortgage can be secured by one or more properties, depending on the financing arrangement.

  • Interest rates: Interest rate arrangements can change over time. A loan part may therefore have multiple consecutive interest rate periods.

  • Payments: Customers make payments towards their mortgage. These payments are allocated to individual loan parts and may consist of principal and interest components.

I was struggling a bit with the concept "interest period/rates". In my opinion not a real business concept in the Conceptual Data Model. For now It will be part of the Loan Part entity. Later on we will model this as an entity in the Logical Data Model (LDM)


We will use these business scenarios as the starting point for designing our conceptual data model.


The objective is not to model every possible detail of a real-world mortgage business. Instead, we want to establish a clear and consistent foundation that we can gradually extend as the project evolves.


This model will become the basis for the subsequent logical and physical data models that we will implement in Databricks using Unity Catalog and Delta tables.


Identifying the business concepts

For our mortgage domain, I identified the following main business concepts:

  • Customer
  • Person
  • Organization
  • Mortgage
  • Loan Part
  • Property
  • Interest Rate Period
  • Payment

Each concept represents something meaningful in the mortgage business. An important design decision is that a customer is not necessarily an individual person. A customer can also be an organization, such as a property investment company. A first draft of the business concepts : 





So thats it for now. I will continue in the next blogposts!


Good AI starts with a good understanding of the business data.

vrijdag 4 december 2026

Databricks series : AI Project: Organizing a Databricks Project with Unity Catalog Schemas

Introduction

Now that the dedicated mortgage_ai_lab catalog has been created, it's time to organize the project. I'll use four schemas based on the Medallion Architecture, with an additional schema for AI-related assets.


We are building upon what we already have :


Create the schemas

In this small blogpost I'll describe the schemas that are created.


CREATE SCHEMA IF NOT EXISTS mortgage_ai_lab.bronze
COMMENT 'Raw source data';

CREATE SCHEMA IF NOT EXISTS mortgage_ai_lab.silver
COMMENT 'Cleansed and validated data';

CREATE SCHEMA IF NOT EXISTS mortgage_ai_lab.gold
COMMENT 'Business-ready analytical data';

CREATE SCHEMA IF NOT EXISTS mortgage_ai_lab.ai
COMMENT 'AI-related assets and supporting data';


Each schema has its own responsibility:

  • Bronze: stores raw data as received from source systems.

  • Silver: contains cleansed, validated and structured data.

  • Gold: provides business-ready data for analytics and reporting.

  • AI: organizes AI-related assets and supporting data.


The project now has a clear structure, separating raw data, refined data, analytical models and AI-related components. In the next step, I'll design the mortgage domain and create the first synthetic source datasets that will feed the Bronze layer.

donderdag 3 december 2026

Databricks series : Understanding schema flexibility with STRUCT, ARRAY, MAP and VARIANT

Introduction

When working with JSON data in Databricks, you will often encounter complex data types such as STRUCT, ARRAY, MAP and VARIANT.  At first glance, these types may look quite similar. They all allow you to work with nested or semi-structured data.  However, there is an important difference: how flexible is the structure of your data?


For example:

  • Can a JSON record contain a field that another record does not have?
  • Can an ARRAY contain a different number of elements?
  • Can a MAP contain different keys for each record?
  • Can every record have a completely different structure?

In this article, we will explore these questions and explain how STRUCT, ARRAY, MAP and VARIANT handle differences in data structures.


We are building upon what we already have :


STRUCT : A fixed structure with optional values

A STRUCT represents an object with a predefined set of named fields. For example, imagine that we define the following STRUCT:


STRUCT<
    customer_id: INT,
    name: STRING,
    country: STRING,
    email: STRING
>


We have defined four fields:

  • customer_id
  • name
  • country
  • email

Does this mean that every customer must have a value for all four fields? No. A field can contain NULL.



Sarah does not have an email address. That is perfectly valid.  The important distinction is that the email field is still part of the STRUCT definition. Its value is simply NULL. Key takeaway: STRUCT has a fixed schema, but individual field values can be NULL.


ARRAY : A collection with a consistent element type

An ARRAY represents a collection of elements. An important rule is that all elements in an ARRAY must have the same data type.  For example:


ARRAY<STRING>


The following values are valid:

["Dutch", "English", "French"]


An ARRAY can also contain NULL elements:

["Dutch", null, "French"]


The number of elements does not have to be the same in every record.  For example, one customer could have three languages while another customer has only one.


ARRAY containing STRUCTs

An ARRAY can also contain more complex elements, such as STRUCTs.


For example:

ARRAY<
    STRUCT<
        order_id: INT,
        amount: DECIMAL(10,2)
    >
>


This represents a list of orders.  Each order has the same structure:

  • order_id
  • amount

You can have different numbers of orders, but every order follows the same STRUCT definition. The amount field can still contain NULL if it is nullable. Key takeaway: ARRAY allows a variable number of elements, but the element type remains consistent.


MAP : Different keys for different records

A MAP is a collection of key-value pairs.  For example:

MAP<STRING, STRING>


This means: Keys are STRING values.  alues are STRING values.  But here is an important difference compared with STRUCT.  The actual keys do not have to be the same in every record.


Consider these two customer records.


Customer 1

{
    "language": "Dutch",
    "currency": "EUR"
}


Customer 2

{
    "language": "English",
    "theme": "dark"
}


Both records are valid MAP values. Customer 1 has a currency key, while customer 2 has a theme key. The MAP definition remains the same because both records use STRING keys and STRING values. If you try to retrieve a key that does not exist, the result is NULL.


For example:

SELECT
    element_at(preferences, 'currency') AS currency
FROM main.demo.customer_preferences;


For customer 2, this returns NULL because the currency key is not present.

Key takeaway: MAP has fixed key and value data types, but the actual keys can differ between records.


VARIANT : A completely flexible structure

VARIANT takes flexibility one step further. Unlike STRUCT, ARRAY and MAP, VARIANT does not require you to define the complete structure in advance. Each record can contain different fields, nested objects, arrays and values. Consider these three JSON records.


Record 1

{
    "customer_id": 1001,
    "name": "Jan",
    "country": "Netherlands"
}


Record 2

{
    "customer_id": 1002,
    "name": "Sarah",
    "preferences": {
        "language": "English"
    },
    "orders": [5001, 5002]
}


Record 3

{
    "customer_id": 1003,
    "name": "Peter",
    "email": "peter@example.com",
    "active": true
}


Notice that the three records have different structures.

  • Record 1 contains a country.

  • Record 2 contains preferences and an array of orders.

  • Record 3 contains an email address and an active flag.

All three records can be stored in the same VARIANT column.


For example:

CREATE OR REPLACE TABLE main.demo.customer_variant
(
    payload VARIANT
);


You can insert the JSON documents using PARSE_JSON():

INSERT INTO main.demo.customer_variant
VALUES
(
    PARSE_JSON(
        '{"customer_id":1001,"name":"Jan","country":"Netherlands"}'
    )
),
(
    PARSE_JSON(
        '{"customer_id":1002,"name":"Sarah","preferences":{"language":"English"},"orders":[5001,5002]}'
    )
),
(
    PARSE_JSON(
        '{"customer_id":1003,"name":"Peter","email":"peter@example.com","active":true}'
    )
);


You can then extract fields using the VARIANT path syntax:

SELECT
    payload:customer_id::INT AS customer_id,
    payload:name::STRING AS customer_name,
    payload:country::STRING AS country,
    payload:email::STRING AS email
FROM main.demo.customer_variant;


Fields that are not present in a particular record return NULL.  This makes VARIANT especially useful when ingesting data from external APIs or event streams where the JSON structure can change over time.


Key takeaway: VARIANT allows each record to have a different structure within the same column.


5. Comparing the four data types

Let's summarize the differences.




There is one important detail:

  • STRUCT has fixed field names, but values can be NULL.

  • ARRAY has a fixed element type, but the number of elements can vary.

  • MAP has fixed key and value types, but the actual keys can vary.

  • VARIANT allows the entire JSON structure to vary.


6. When should you use which data type?

A simple rule of thumb:


Use STRUCT when:

  • You know the fields in advance.

  • You want a clearly defined schema.

  • You are working with objects such as customer addresses or product details.


Use ARRAY when:

  • You have a list of repeating elements.

  • You want to store multiple values of the same type.

  • You are working with orders, transactions or event collections.


Use MAP when:

  • You have dynamic attributes.

  • The keys can differ between records.

  • You want to store flexible key-value pairs.


Use VARIANT when:

  • You do not know the complete JSON structure in advance.

  • The structure can change between records.

  • You are ingesting data from external APIs or event streams.


Conclusion

STRUCT, ARRAY, MAP and VARIANT all help us work with complex data in Databricks, but they offer different levels of flexibility. The main difference is not whether a value can be NULL. Even a STRUCT can contain NULL values. The real difference is how much of the data structure must be defined in advance. STRUCT, ARRAY and MAP have defined type structures, while VARIANT allows the complete structure to vary between records.This is particularly useful when designing a data ingestion process. You can initially store flexible JSON payloads using VARIANT and then extract and validate the fields you need in your Prep layer.


In other words:

Use VARIANT when you need flexibility at ingestion time, and use STRUCT, ARRAY and MAP when you want more explicitly defined data structures.


Databricks series : Starting a New Databricks AI Project: Creating a Dedicated Unity Catalog

Introduction

I am starting a New Databricks AI Project and I will start with creating a dedicated Unity Catalog. When starting a new data engineering or AI project in Databricks, I prefer to begin with a clean and well-organized environment.  Rather than using an existing catalog or mixing the project with other experiments, I want to create a dedicated Unity Catalog catalog for the project.


In this blog post, I'll show how to create a new catalog in Databricks Free Edition and prepare the foundation for a larger Data Architecture and AI project.


We are building upon what we already have :


The project: Mortgage AI Lab

For this learning project, I will build a small but realistic mortgage data platform. The idea is to gradually develop a solution that combines:

  • Data Engineering with PySpark and SQL.
  • Delta Lake and the Medallion Architecture.
  • Data Modelling and Semantic Modelling.
  • Unity Catalog and Data Governance.
  • AI-powered analytics and AI Agents.


The ultimate goal is to make mortgage data accessible not only through traditional SQL queries and dashboards, but also through AI-powered applications that can understand and answer questions about the underlying business data.


Before building any pipelines or loading data, I want to establish a dedicated project structure.


Why create a separate catalog?

Databricks Unity Catalog provides a centralized way to organize and govern data assets. The hierarchy is:

Metastore → Catalog → Schema → Tables, Views and other objects


A catalog is a useful top-level boundary for organizing a project. By creating a dedicated catalog, I can:

  • Keep this project separate from existing exercises and datasets.
  • Organize data assets in a consistent way.
  • Apply permissions and governance independently.
  • Build a structure that can grow as the project evolves.

In my Databricks Free Edition workspace, I can already see several existing catalogs, including main, samples, system and workspace. However, I don't want to use any of these for my new project. Instead, I'll create a dedicated catalog called mortgage_ai_lab.


3. Creating the catalog

First, open a new notebook in your Databricks workspace. Select SQL as the notebook language and execute the following statement:

%sql
CREATE CATALOG IF NOT EXISTS mortgage_ai_lab
COMMENT 'Independent learning project for Databricks Data Architecture and AI';

SHOW CATALOGS;


The CREATE CATALOG statement creates the new catalog if it does not already exist. The COMMENT provides a short description of the catalog, explaining its purpose. Finally, SHOW CATALOGS lists the catalogs available in the current metastore. You should now see mortgage_ai_lab in the result.


Note: Creating a catalog requires the appropriate CREATE CATALOG privileges on the metastore. If you receive a permission error, check the permissions associated with your Databricks workspace and user.


Planning the project structure

The catalog is now created, but it does not contain any schemas or tables yet. I plan to organize the project using a structure inspired by the Medallion Architecture:


mortgage_ai_lab
│
├── bronze
│   └── Raw source data
│
├── silver
│   └── Cleansed and validated data
│
├── gold
│   └── Business-ready and analytical data
│
└── ai
    └── AI-related assets and supporting data


Each of these folders will eventually become a separate Unity Catalog schema. This gives the project a clear separation between raw data, refined data, business-ready data and AI-related assets. I'll create these schemas in the next step.


What comes next?

With the catalog in place, the foundation of the project is ready.In the next part of this series, I'll create the schemas and start designing the mortgage domain.


The domain will include concepts such as:

  • Customers
  • Mortgages
  • Mortgage loan components
  • Properties used as collateral
  • Interest rates
  • Payments and repayments


From there, I'll build the data pipelines, develop the data models and eventually connect the data to AI capabilities.The objective is not simply to build another Databricks pipeline. I want to explore how good data architecture, clear business definitions and semantic modelling can provide reliable context for AI applications and agents. A good AI solution starts with well-structured and well-understood data.

zondag 29 november 2026

Databricks Series : Working with JSON in Databricks SQL : VARIANT

Introduction

In the previous articles, we explored three important complex data types in Databricks SQL: STRUCT, ARRAY and MAP. These types are useful when working with nested data. But what happens when the structure of your incoming JSON data is not always the same?


For example:

  • One JSON record contains a phone_number, while another does not.
  • A new API version introduces additional fields.
  • Different records contain different attributes.
  • You do not know the complete JSON structure in advance.


This is where the VARIANT data type becomes useful.In this article, we will explore what VARIANT is, how to store JSON data in a VARIANT column, and how to extract fields from it using Databricks SQL.


We are building upon what we already have :


What is VARIANT?

VARIANT is a data type designed for storing semi-structured data. Unlike a STRUCT, where you define the fields and their data types in advance, VARIANT allows you to store JSON data without having to define the complete structure first. For example, imagine that you receive these two JSON records:


record 1 

{
  "customer_id": 1001,
  "name": "Jan Jansen",
  "country": "Netherlands"
}


Record 2

{
  "customer_id": 1002,
  "name": "Sarah Johnson",
  "country": "USA",
  "email": "sarah@example.com",
  "preferences": {
    "language": "English",
    "newsletter": true
  }
}


Both records have some common fields, but the second record contains additional information. With a traditional STRUCT, you would need to define a schema that accommodates these fields. With VARIANT, you can store both JSON records in the same column without first defining all their fields.


This makes VARIANT particularly useful when working with:

  • REST APIs
  • JSON files
  • Event streams
  • Changing data structures
  • Semi-structured source data


2. Create a table with a VARIANT column

Let's start by creating a table in Databricks. We will store the customer information in a column called payload.


CREATE OR REPLACE TABLE main.demo.customer_variant
(
    payload VARIANT
);


Notice that we do not define individual columns for customer_id, name or country. The complete JSON document will be stored in the payload column.


Insert JSON data using PARSE_JSON

To convert a JSON string into a VARIANT value, Databricks provides the PARSE_JSON() function.

Let's insert two customer records.



INSERT INTO main.demo.customer_variant
VALUES
(
    PARSE_JSON(
        '{
            "customer_id": 1001,
            "name": "Jan Jansen",
            "country": "Netherlands"
        }'
    )
),
(
    PARSE_JSON(
        '{
            "customer_id": 1002,
            "name": "Sarah Johnson",
            "country": "USA",
            "email": "sarah@example.com",
            "preferences": {
                "language": "English",
                "newsletter": true
            }
        }'
    )
);


The PARSE_JSON() function converts the JSON string into a VARIANT value. You can now query the table:


SELECT *
FROM main.demo.customer_variant;


Results in :




The complete JSON document is stored in one column.


4. Extract fields from VARIANT

Storing the complete JSON document is useful, but in most cases you also want to access individual fields. Databricks SQL supports the colon (:) operator to navigate through VARIANT data.

For example:


SELECT
    payload:customer_id AS customer_id,
    payload:name AS customer_name,
    payload:country AS country
FROM main.demo.customer_variant;


Results in :



You may notice that the extracted values are still VARIANT values.


SELECT
    TYPEOF(payload) AS payload_type,
    TYPEOF(payload:customer_id) AS customer_id_type,
    TYPEOF(payload:name) AS name_type
FROM main.demo.customer_variant;


Resulting in : 



 If you want to work with them as regular SQL data types, you can cast them.


SELECT
    payload:customer_id::INT AS customer_id,
    payload:name::STRING AS customer_name,
    payload:country::STRING AS country
FROM main.demo.customer_variant;


Resulting in :




Now the extracted fields have explicit SQL data types.


5. Access nested fields

VARIANT also supports nested JSON structures. Remember that our second customer record contains a preferences object:


{
  "preferences": {
    "language": "English",
    "newsletter": true
  }
}


You can access nested fields using the same colon notation.


SELECT
    payload:customer_id::INT AS customer_id,
    payload:preferences:language::STRING AS language,
    payload:preferences:newsletter::BOOLEAN AS newsletter
FROM main.demo.customer_variant;


REsulting in : 




The result for the first customer will contain NULL values because that record does not have a preferences object. The second customer will return the language and newsletter preference. This is one of the benefits of VARIANT: records do not all need to contain exactly the same fields.


Access arrays inside VARIANT

VARIANT can also contain arrays. Let's insert another customer with a list of orders.


INSERT INTO main.demo.customer_variant
VALUES
(
    PARSE_JSON(
        '{
            "customer_id": 1003,
            "name": "Peter Smith",
            "country": "UK",
            "orders": [
                {
                    "order_id": 5001,
                    "amount": 125.50
                },
                {
                    "order_id": 5002,
                    "amount": 89.99
                }
            ]
        }'
    )
);


You can access an individual array element using its index. Remember that array indexing starts at zero.


SELECT
    payload:customer_id::INT AS customer_id,
    payload:orders[0]:order_id::INT AS first_order_id,
    payload:orders[0]:amount::DECIMAL(10,2) AS first_order_amount
FROM main.demo.customer_variant;


Resulting in :




This example retrieves the first order from the array.  If you want to retrieve all orders as separate rows, you can use VARIANT_EXPLODE. This turns the array elements into separate rows.  


Inspect the structure of VARIANT data

Sometimes you receive JSON data without knowing its exact structure. Databricks provides the SCHEMA_OF_VARIANT() function to inspect the structure of an individual VARIANT value.


SELECT
    SCHEMA_OF_VARIANT(payload) AS detected_schema
FROM main.demo.customer_variant;


This returns a schema description based on the contents of the VARIANT value. You can also use SCHEMA_OF_VARIANT_AGG() to derive a combined schema from multiple records.


SELECT
    SCHEMA_OF_VARIANT_AGG(payload) AS combined_schema
FROM main.demo.customer_variant;


Resulting in :





This can be helpful when exploring new or changing data sources.


8. Handle invalid JSON

What happens when the incoming JSON is not valid? For example:


{
  "customer_id": 1004,
  "name": "Invalid JSON"


The JSON document is missing a closing brace. Using PARSE_JSON() on malformed JSON raises an error.  If you prefer to return NULL instead of stopping the operation, you can use TRY_PARSE_JSON().


SELECT
    TRY_PARSE_JSON('{"customer_id": 1004, "name": "Invalid JSON"') AS payload;



This returns NULL when the JSON cannot be parsed. This can be useful when ingesting data from external systems where the input is not always reliable.


VARIANT versus STRUCT, ARRAY and MAP

We have now seen how VARIANT works. But when should you use it instead of STRUCT, ARRAY or MAP?




A simple rule of thumb:

  • Use STRUCT when you know the structure and want strongly typed fields.

  • Use ARRAY when you need an ordered list of values.

  • Use MAP when you need key-value pairs.

  • Use VARIANT when the structure of your incoming data can change or is not known in advance.

VARIANT does not mean that you should store every field in one JSON column forever. If you frequently query fields such as customer_id, country or event_timestamp, it is often better to extract those fields into regular typed columns. This makes the data easier to use in analytical queries and helps with data organization and performance.


Important considerations

There are a few things to keep in mind when using VARIANT in Databricks:

  • VARIANT is supported in Databricks SQL and Databricks Runtime 15.3 and above.
  • VARIANT is designed for semi-structured data such as JSON objects, arrays and scalar values.
  • JSON field names are case-sensitive.
  • A VARIANT column cannot be used as a partitioning or clustering key, or in operations such as GROUP BY and ORDER BY.
  • Frequently queried fields should generally be extracted into regular columns.

Always check the supported features of the Databricks Runtime or SQL warehouse you are using.


Conclusion

The VARIANT data type adds another useful option when working with semi-structured data in Databricks. Where STRUCT, ARRAY and MAP require you to work with defined data structures, VARIANT gives you more flexibility when the structure of your incoming JSON data is unknown or changes over time.  It is particularly useful in ingestion and raw data layers, where you may want to preserve the original payload before deciding how to transform and model it. Once the data is understood, you can extract the relevant fields and move them into structured tables for further processing and analytics.


In short: VARIANT gives you flexibility at ingestion time, while STRUCT, ARRAY and MAP provide more explicitly defined structures for working with your data.