zaterdag 28 november 2026

Databricks Series : Working with JSON in Databricks SQL : MAP

Introduction

A MAP is a collection of key-value pairs. It is similar to a Python dictionary. Unlike a STRUCT, a MAP is useful when the available keys may vary between records. 


We are building upon what we already have :


Example JSON

Imagine that a customer has several preferences:


{
  "customer_id": 1001,
  "preferences": {
    "language": "Dutch",
    "currency": "EUR",
    "newsletter": "true",
    "theme": "dark"
  }
}

The preferences property contains dynamic attributes. We can represent this using:


MAP<STRING, STRING>


This means that both the keys and values are strings. 


Create a source table


CREATE OR REPLACE TABLE main.demo.customer_map_json
(
    customer_id BIGINT,
    payload STRING
);


Insert an example record:


INSERT INTO main.demo.customer_map_json
VALUES (
    1001,
    '{
      "customer_id": 1001,
      "preferences": {
        "language": "Dutch",
        "currency": "EUR",
        "newsletter": "true",
        "theme": "dark"
      }
    }'
);


Parse the JSON

Use from_json() to convert the preferences object into a MAP.


SELECT
    from_json(
        payload,
        'STRUCT<
            customer_id: BIGINT,
            preferences: MAP<STRING, STRING>
        >'
    ) AS customer

FROM main.demo.customer_map_json;


Results in 




Now Spark understands that preferences is a MAP.


Extract individual values

We can retrieve values using element_at().


SELECT
    customer.customer_id,

    element_at(
        customer.preferences,
        'language'
    ) AS language,

    element_at(
        customer.preferences,
        'currency'
    ) AS currency,

    element_at(
        customer.preferences,
        'newsletter'
    ) AS newsletter,

    element_at(
        customer.preferences,
        'theme'
    ) AS theme

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                preferences: MAP<STRING, STRING>
            >'
        ) AS customer

    FROM main.demo.customer_map_json
);

Resulting in




Notice that we can retrieve individual values by specifying their keys. If a key does not exist, element_at() returns NULL.

Expand all MAP entries

Sometimes we don't know which keys are present. In that situation, we can use EXPLODE on the MAP itself.


SELECT
    customer.customer_id,
    preference_key,
    preference_value

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                preferences: MAP<STRING, STRING>
            >'
        ) AS customer

    FROM main.demo.customer_map_json
) parsed

LATERAL VIEW EXPLODE(customer.preferences)
    exploded AS preference_key, preference_value;


Results in : 





This is particularly useful when you want to inspect all available attributes without knowing the keys in advance.


Create a SQL View

For a fixed set of attributes, we can create a regular view:


CREATE OR REPLACE VIEW main.demo.v_customer_preferences AS

SELECT
    customer.customer_id,

    element_at(
        customer.preferences,
        'language'
    ) AS language,

    element_at(
        customer.preferences,
        'currency'
    ) AS currency,

    element_at(
        customer.preferences,
        'newsletter'
    ) AS newsletter,

    element_at(
        customer.preferences,
        'theme'
    ) AS theme

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                preferences: MAP<STRING, STRING>
            >'
        ) AS customer

    FROM main.demo.customer_map_json
);


Query the view:

SELECT *
FROM main.demo.v_customer_preferences;




MAP is useful for dynamic attributes where you cannot always predict which keys will be available.

Examples include:

  • Customer preferences
  • Product attributes
  • API metadata
  • Event properties
  • Dynamic configuration values

If the keys are known and stable, a STRUCT is often a better choice because it provides a clearly defined schema


4. Comparing STRUCT, ARRAY and MAP

We have now seen all three complex data types.



A simple way to remember the difference:

  • STRUCT: one object with multiple attributes.
  • ARRAY: multiple elements, often repeating objects.
  • MAP: dynamically named attributes.


Choosing the right approach for your Databricks architecture


When working with JSON in a Medallion Architecture, I would generally separate the responsibilities.


Raw layer

Keep the original JSON data. This preserves the source information and allows you to reprocess it if the schema changes.


Base layer

Store the ingested data in Delta tables. Depending on the ingestion design, the JSON can remain a STRING or be parsed into complex Spark types.


Prep layer

Parse the JSON using from_json(), validate the structure and extract the attributes needed for downstream processing.


Gold layer

Expose business-friendly SQL Views or tables with clear relational columns.


RAW
 |
 | Original JSON
 v
BASE
 |
 | Delta tables
 v
PREP
 |
 | STRUCT / ARRAY / MAP parsing
 | Data validation
 v
GOLD
 |
 | SQL Views
 | Business-ready columns
 v
Reporting / Analytics


Conclusion

Databricks SQL provides powerful functionality for working with semi-structured JSON data. With from_json(), we can convert JSON strings into typed structures. We can then use dot notation to access STRUCT fields, EXPLODE() to expand ARRAY elements and ELEMENT_AT() to retrieve values from MAPs. Instead of keeping complex JSON documents in a single column, we can expose the information through reusable SQL Views. 


The key is to understand the structure of the JSON first and choose the appropriate Spark data type. Once you understand STRUCT, ARRAY and MAP, working with nested JSON in Databricks becomes much easier.

Databricks series : Working with JSON in Databricks SQL : ARRAY

Introduction

An ARRAY represents a collection of elements. A common example is an order list belonging to a customer. One customer can have multiple orders, and each order contains several attributes.


We are building upon what we already have :


An example 


{
  "customer_id": 1001,
  "name": "Jan Jansen",
  "orders": [
    {
      "order_id": "ORD001",
      "amount": 125.50,
      "status": "COMPLETED"
    },
    {
      "order_id": "ORD002",
      "amount": 89.95,
      "status": "OPEN"
    }
  ]
}


The orders property is an ARRAY.

Each element inside the ARRAY is a STRUCT containing:

  • order_id

  • amount

  • status

The resulting Spark data type is conceptually:


Create a source table

Lets create a table :

CREATE OR REPLACE TABLE main.demo.customer_array_json
(
    customer_id BIGINT,
    payload STRING
);

Insert the example data:


INSERT INTO main.demo.customer_array_json
VALUES (
    1001,
    '{
      "customer_id": 1001,
      "name": "Jan Jansen",
      "orders": [
        {
          "order_id": "ORD001",
          "amount": 125.50,
          "status": "COMPLETED"
        },
        {
          "order_id": "ORD002",
          "amount": 89.95,
          "status": "OPEN"
        }
      ]
    }'
);


Parse the JSON

We use from_json() again, but this time we define an ARRAY containing STRUCT elements.


SELECT
    from_json(
        payload,
        'STRUCT<
            customer_id: BIGINT,
            name: STRING,
            orders: ARRAY<
                STRUCT<
                    order_id: STRING,
                    amount: DOUBLE,
                    status: STRING
                >
            >
        >'
    ) AS customer

FROM main.demo.customer_array_json;

Now Spark understands that orders contains multiple order objects. 




Expand the ARRAY using EXPLODE


How do we turn the individual orders into separate rows? For this, we use EXPLODE().

SELECT
    customer.customer_id,
    customer.name,
    order.order_id,
    order.amount,
    order.status

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                name: STRING,
                orders: ARRAY<
                    STRUCT<
                        order_id: STRING,
                        amount: DOUBLE,
                        status: STRING
                    >
                >
            >'
        ) AS customer

    FROM main.demo.customer_array_json
) parsed

LATERAL VIEW EXPLODE(customer.orders) exploded AS order;

Resulting in : 




Notice what happened: one customer record became two rows because the customer has two orders. This is an important difference compared with STRUCT. A STRUCT extracts fields from an existing row, while EXPLODE expands an ARRAY into multiple rows.


Create a SQL View

We can make this transformation reusable by creating a view.


CREATE OR REPLACE VIEW main.demo.v_customer_orders AS

SELECT
    customer.customer_id,
    customer.name,
    order.order_id,
    order.amount,
    order.status

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                name: STRING,
                orders: ARRAY<
                    STRUCT<
                        order_id: STRING,
                        amount: DOUBLE,
                        status: STRING
                    >
                >
            >'
        ) AS customer

    FROM main.demo.customer_array_json
) parsed

LATERAL VIEW EXPLODE(customer.orders) exploded AS order;

Query the view:


SELECT *
FROM main.demo.v_customer_orders;

ARRAY is useful when a JSON document contains lists of repeating elements, such as:

  • Customer orders

  • Product items

  • Transaction lines

  • Event collections

  • API result lists

One important consideration: EXPLODE changes the granularity of the data. If one customer has five orders, the resulting dataset contains five rows for that customer.

vrijdag 27 november 2026

Databricks series : Working with JSON in Databricks SQL : STRUCT

Introduction

JSON is a very common data format when working with APIs, event streams and semi-structured data. In Databricks, JSON data can be stored in a single column, but this does not mean that we have to keep working with it as one large JSON string. Databricks SQL provides several functions to parse JSON and extract individual attributes into relational columns.


In these articles, we will explore three important complex data types :

  • STRUCT : an object containing named fields.
  • ARRAY : a collection of elements.
  • MAP  : a collection of key-value pairs.

For each type, we will create a separate example, store the JSON in a table, parse it and create a SQL View that exposes the data as regular columns.


All examples use Databricks SQL.


We are building upon what we already have :


What is a struct

A STRUCT represents an object containing multiple named fields. It is similar to an object in JSON or a dictionary in Python.  A typical example is a customer address.


Imagine that an API returns the following customer information:

{
  "customer_id": 1001,
  "name": "Jan Jansen",
  "address": {
    "street": "Hoofdstraat 10",
    "city": "Utrecht",
    "country": "Netherlands"
  }
}


The address property is a nested JSON object.  In Databricks, we can represent this as a STRUCT containing three fields: street, city, country


Create a source table

First, we create a table with a JSON string column.


CREATE OR REPLACE TABLE main.demo.customer_struct_json
(
    customer_id BIGINT,
    payload STRING
);

Insert an example record:


INSERT INTO main.demo.customer_struct_json
VALUES (
    1001,
    '{
      "customer_id": 1001,
      "name": "Jan Jansen",
      "address": {
        "street": "Hoofdstraat 10",
        "city": "Utrecht",
        "country": "Netherlands"
      }
    }'
);

At this point, the complete JSON document is stored in one STRING column called payload.


Parse the JSON using from_json()

We can use the Databricks SQL function from_json() to convert the JSON string into a structured data type.


SELECT
    from_json(
        payload,
        'STRUCT<
            customer_id: BIGINT,
            name: STRING,
            address: STRUCT<
                street: STRING,
                city: STRING,
                country: STRING
            >
        >'
    ) AS customer
FROM main.demo.customer_struct_json;

Resulting in : 




We explicitly define the expected schema. Notice that address is itself a STRUCT nested inside another STRUCT.


Extract individual fields

Once the JSON has been parsed, we can use dot notation to access individual fields.


SELECT
    customer.customer_id,
    customer.name,
    customer.address.street AS street,
    customer.address.city AS city,
    customer.address.country AS country

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                name: STRING,
                address: STRUCT<
                    street: STRING,
                    city: STRING,
                    country: STRING
                >
            >'
        ) AS customer

    FROM main.demo.customer_struct_json
);

Resulting in : 




Create a reusable SQL View

Instead of repeating the JSON parsing logic, we can create a view.


CREATE OR REPLACE VIEW main.demo.v_customer_struct AS

SELECT
    customer.customer_id,
    customer.name,
    customer.address.street AS street,
    customer.address.city AS city,
    customer.address.country AS country

FROM (
    SELECT
        from_json(
            payload,
            'STRUCT<
                customer_id: BIGINT,
                name: STRING,
                address: STRUCT<
                    street: STRING,
                    city: STRING,
                    country: STRING
                >
            >'
        ) AS customer

    FROM main.demo.customer_struct_json
);

STRUCT is ideal when your JSON contains objects with known fields, such as:

  • Customer addresses
  • Product details
  • Shipping information
  • Contact information
  • Nested API response objects

The important thing to remember is that STRUCT fields can be accessed directly using dot notation.



Databricks series : Building a mediallion architecture with SCD Type 2 (step 3) (Part XIV)

Introduction

In this step, we'll take the CSV files from your Raw Volume and ingest them into a Delta table in the Base layer. We'll also enable Delta Change Data Feed (CDF). We'll do this without breaking our existing customer and API pipelines.


We are building upon what we already have :

We'll build a Python ingestion process that reads the CSV files from the Raw Volume and appends them to Delta tables in the Base layer. We'll also add technical metadata such as: Source file, Source system, Ingestion timestamp and Batch ID


Check the RAW files

First, make sure your two CSV files are in this location:

/Volumes/main/raw/files/customers.csv
/Volumes/main/raw/files/customers_update.csv

Open a Databricks notebook and execute:

dbutils.fs.mkdirs(
    "/Volumes/main/raw/files/customers"
)

dbutils.fs.cp(
    "dbfs:/Volumes/main/demo/raw/customers.csv",
    "dbfs:/Volumes/main/raw/files/customers.csv"
)

dbutils.fs.cp(
    "dbfs:/Volumes/main/demo/raw/customers_update.csv",
    "dbfs:/Volumes/main/raw/files/customers_update.csv"
)

Resulting in : 



Check the files:
display(
    dbutils.fs.ls(
        "/Volumes/main/raw/files/customers/"
    )
)

Resulting in : 




You should see the files.


Update entities.json

Open config/entities.json in Visual Studio Code. Add two new configurations inside the existing JSON object. Keep your existing configurations.


  "customers_base": {
  "source": "/Volumes/main/raw/files/customers.csv",
  "source_type": "csv",
  "source_system": "customer_csv",
  "format": "csv",
  "target": "main.base.customers",
  "mode": "base"
  },
  "customers_update_base": {
    "source": "/Volumes/main/raw/files/customers_update.csv",
    "source_type": "csv",
    "source_system": "customer_csv",
    "format": "csv",
    "target": "main.base.customers",
    "mode": "base"
  }

Both configurations write to the same Delta table. The difference is the input file.


Create base_writer.py

Now we'll create a dedicated Python module for Base ingestion.

Create this new file:

src/transfer/base_writer.py

Paste the following complete code:

import uuid

from pyspark.sql.functions import (
    current_timestamp,
    lit
)


def ingest_to_base(spark, config):

    source = config["source"]
    target = config["target"]
    source_type = config.get("source_type", "csv")
    source_system = config.get("source_system", source_type)
    file_format = config.get("format", "csv")

    if source_type != "csv":
        raise ValueError(
            f"Unsupported source type: {source_type}"
        )

    print(f"Reading raw file: {source}")
    print(f"Target Base table: {target}")

    # Read source file
    df = (
        spark.read
        .format(file_format)
        .option("header", "true")
        .option("inferSchema", "false")
        .load(source)
    )

    # Generate ingestion metadata
    batch_id = str(uuid.uuid4())

    base_df = (
        df
        .withColumn(
            "_ingestion_timestamp",
            current_timestamp()
        )
        .withColumn(
            "_source_system",
            lit(source_system)
        )
        .withColumn(
            "_source_file",
            lit(source)
        )
        .withColumn(
            "_batch_id",
            lit(batch_id)
        )
    )

    record_count = base_df.count()

    print(f"Batch ID: {batch_id}")
    print(f"Records to ingest: {record_count}")

    # Check whether the Delta table already exists
    table_exists = spark.catalog.tableExists(target)

    if table_exists:

        # Enable CDF before appending new records
        spark.sql(f"""
            ALTER TABLE {target}
            SET TBLPROPERTIES (
                delta.enableChangeDataFeed = true
            )
        """)

        (
            base_df.write
            .format("delta")
            .mode("append")
            .saveAsTable(target)
        )

    else:

        # Initial load
        (
            base_df.write
            .format("delta")
            .mode("overwrite")
            .saveAsTable(target)
        )

        # Enable CDF after initial table creation
        spark.sql(f"""
            ALTER TABLE {target}
            SET TBLPROPERTIES (
                delta.enableChangeDataFeed = true
            )
        """)

    print(
        f"Base ingestion completed: "
        f"{record_count} records written to {target}"
    )

What does this code do?

  1. Reads the CSV file from Raw.

  2. Adds technical metadata.

  3. Generates a unique batch ID.

  4. Creates the Base Delta table on the first run.

  5. Appends records on subsequent runs.

  6. Enables Change Data Feed on the table.

Notice that we don't apply business transformations here. Base is intended to preserve the ingested source records.


Connect the new module to main.py

We need to tell our application when to use the new Base ingestion process. Open: src/main.py First, add this import:


from transfer.base_writer import ingest_to_base

Now find the existing code where you load the contract:


contract_path = project_root / config["contract"]

with open(contract_path, "r", encoding="utf-8") as file:
    contract = yaml.safe_load(file)

transfer_data(spark, config, contract)

Replace that entire section with:

if config.get("mode") == "base":

    print("Starting Raw to Base ingestion")

    ingest_to_base(
        spark,
        config
    )

else:

    contract_path = project_root / config["contract"]

    with open(contract_path, "r", encoding="utf-8") as file:
        contract = yaml.safe_load(file)

    transfer_data(
        spark,
        config,
        contract
    )

This is important: Base ingestion doesn't need an ODCS contract yet. We'll introduce contract validation in the Prep layer. Your existing customer and API processes will continue using transfer_data().


Step 5 – Deploy to Databricks

Open your VS Code terminal. Run:


databricks bundle validate -t dev


If validation succeeds:

databricks bundle deploy -t dev


Execute the initial ingestion

Run the first job:


databricks bundle run transfer_job -t dev --params entity=customers_base

This reads customers.csv and creates:

main.base.customers


Next, ingest the update file :

databricks bundle run transfer_job -t dev --params entity=customers_update_base

This appends the records from customers_update.csv to the same table.  The Base table should contain the initial customers and the update records. This first implementation appends every time you run it. Don't rerun the same ingestion entity unnecessarily, because that would create duplicate records. We'll add ingestion tracking and safe reprocessing later.

Check the Base table

Open Databricks SQL Editor and run:


SELECT *
FROM main.base.customers
ORDER BY customer_id;

Resulting in  :




You should see your customer data together with the four metadata columns:



You can also inspect the ingestion batches:


SELECT
    _batch_id,
    _source_file,
    COUNT(*) AS record_count
FROM main.base.customers
GROUP BY
    _batch_id,
    _source_file;

Resulting in : 



Verify Change Data Feed

Finally, check whether CDF is enabled:


SHOW TBLPROPERTIES main.base.customers;

Resulting in :


delta.enableChangeDataFeed = true

You can also inspect the Delta table history:


DESCRIBE HISTORY main.base.customers;

Resulting in : 




You should see the initial write, the CDF property change, and the subsequent append. One important detail: CDF was enabled after the initial load. That means the initial customer records are your baseline snapshot; the subsequent update-file ingestion is captured by CDF. This is exactly what we want for the next step.


Hennie

donderdag 26 november 2026

Databricks series : Building a mediallion architecture with SCD Type 2 (step 2) (Part XIII)

Introduction

In this series, we're building a small but realistic data platform using Databricks, Python, Delta Lake, and Unity Catalog. The goal is to create a reusable data ingestion architecture that can handle different data sources, such as CSV files and REST APIs, while supporting incremental processing and historical data tracking. We'll use a Medallion-inspired architecture with four logical layers:

  • Raw : Original source files.

  • Base : Ingested data stored as Delta tables.

  • Prep  : Validated and transformed data, including historical tracking.

  • Gold : Business-ready data for reporting and analytics.

In this first part, we'll focus on preparing the Unity Catalog structure and creating the Raw storage location. We won't build the Python pipelines yet. First, let's get the foundation right.


We are building upon what we already have :


2. Creating the Unity Catalog schemas

We'll use an existing Unity Catalog catalog called main.

Instead of creating separate catalogs for every layer, we'll create four schemas inside the existing catalog:


main
│
├── raw
├── base
├── prep
└── gold

Open the Databricks SQL Editor and execute:


CREATE SCHEMA IF NOT EXISTS main.raw;
CREATE SCHEMA IF NOT EXISTS main.base;
CREATE SCHEMA IF NOT EXISTS main.prep;
CREATE SCHEMA IF NOT EXISTS main.gold;

This creates the logical structure for our data platform. Using schemas for the different layers keeps the data organized and makes access management easier.


3. Creating the Raw Volume

The Raw layer will store our original source files. In Unity Catalog, we'll use a Volume for file storage. Execute the following SQL statement:

CREATE VOLUME IF NOT EXISTS main.raw.files;

Our Raw storage location is now:

/Volumes/main/raw/files/

We'll use this location as the landing zone for incoming files. For example, our folder structure will eventually look like this:


/Volumes/main/raw/files/
│
├── customers/
│   ├── customers.csv
│   └── customers_update.csv
│
└── exchange_rates/
    └── exchange_rates.json


The important design principle is that the Raw layer preserves the original input. We don't apply business transformations or overwrite source files during ingestion. This gives us the possibility to reprocess the original data if something goes wrong in a downstream pipeline.


4. Verifying the Unity Catalog structure

After creating the schemas and Volume, we can verify the setup. To list the schemas we can use the following command :


SHOW SCHEMAS IN main;

Resulting in :




To inspect the Volume:


DESCRIBE VOLUME main.raw.files;



We should now have the following structure available:

main
│
├── raw
│   └── files (Volume)
│
├── base
│
├── prep
│
└── gold

At this stage, the schemas are empty except for the Raw Volume. That's exactly what we want. We're preparing the foundation before implementing the ingestion logic.


5. Moving existing source files

In our existing Python project, we already have two customer CSV files:


/Volumes/main/demo/raw/customers.csv
/Volumes/main/demo/raw/customers_update.csv

We'll move or copy these files into the new Raw Volume:


/Volumes/main/raw/files/customers/customers.csv
/Volumes/main/raw/files/customers/customers_update.csv

So this is the result :


We'll keep the original files until we've verified that the new locations work correctly. This gives us a clean separation between the original landing zone and the future Delta tables.


Conclusion

We've now established the foundation of our Databricks Medallion Architecture. By organizing Unity Catalog into Raw, Base, Prep, and Gold schemas, and creating a dedicated Volume for original source files, we've established a clear separation between file storage, data ingestion, preparation, and business consumption. The next step is to connect these layers with Python and Delta Lake. This is where the architecture starts to become a working data platform.

zondag 22 november 2026

Databricks series : Building a mediallion architecture with SCD Type 2 (Step 1) (Part XII)

Introduction

When building a data platform, simply loading files into Delta tables is rarely enough. As data pipelines grow, we need a structured approach to ingestion, data quality, change tracking, and historical data management.  In this blogpost and other blogposts, we'll build a small but practical data platform using Databricks, Unity Catalog, Delta Lake, Change Data Feed (CDF), and Slowly Changing Dimensions Type 2 (SCD2).


The goal is to create an architecture that can ingest data from different sources, preserve the original input, detect changes, and maintain historical versions of business entities. We'll use customer data as our example, but the same architecture can also support REST APIs and other data sources.



The architecture

We'll use a Medallion-inspired architecture with four logical layers:

  • Raw: Original source files.

  • Base: Ingested data stored as Delta tables.

  • Prep: Validated and transformed data, including historical tracking.

  • Gold: Business-ready data for reporting and analytics.


Each layer has a specific responsibility. This separation makes the platform easier to maintain, troubleshoot, and extend.


2. Raw – Preserve the original data

The Raw layer is our landing zone. Its responsibility is straightforward: store source files exactly as they arrive. For this implementation, we'll use a Unity Catalog Volume:


/Volumes/main/raw/files/

Our folder structure could look like this:


/Volumes/main/raw/files/
    customers/
        customers.csv
        customers_update.csv

    exchange_rates/
        exchange_rates.json


We deliberately avoid business transformations in this layer. The original files remain available for reprocessing, troubleshooting, and auditing. Using a Unity Catalog Volume also provides governed access to files through Databricks.


3. Base – Ingest files into Delta tables

The Base layer converts the files from Raw into Delta tables. For example:


main.base.customers
main.base.exchange_rates


During ingestion, we add technical metadata to each record:




We use append-based ingestion so that incoming records are preserved instead of overwriting previous data. An important feature of this layer is Delta Change Data Feed. We enable CDF on the Base table:


ALTER TABLE main.base.customers
SET TBLPROPERTIES (
    delta.enableChangeDataFeed = true
);


CDF allows downstream processes to read row-level changes made to a Delta table. It exposes metadata such as:

  • _change_type

  • _commit_version

  • _commit_timestamp

This provides an efficient mechanism for incremental processing. One important distinction: when we append records from CSV files, CDF reports those records as inserts. It does not automatically detect that a customer already exists in another batch. That comparison is part of our downstream processing.


Prep – Data quality and historical tracking

The Prep layer is where the actual data preparation takes place.

Here we:

  • Validate incoming data.

  • Apply data types.

  • Remove or handle duplicates.

  • Apply business rules.

  • Detect changes in customer records.

  • Maintain historical versions using SCD Type 2.


We'll use an ODCS Data Contract to describe the expected customer schema and required fields.

For example, a customer contract defines:


schema:
  - name: customers
    properties:
      - name: customer_id
        logicalType: string
        primaryKey: true
        required: true

      - name: first_name
        logicalType: string
        required: true

      - name: last_name
        logicalType: string
        required: true

      - name: country
        logicalType: string
        required: true


The contract describes the expected structure and quality requirements. Our PySpark validation code enforces the selected rules at runtime.


Implementing SCD Type 2

A key requirement in many data platforms is preserving historical changes.


Suppose customer 1002 initially lives in Belgium:

customer_idfirst_namecountry
1002PietBelgium

Later, the customer changes their name and country:

customer_idfirst_namecountry
1002Pieter  Netherlands


A conventional upsert would overwrite the existing record. With SCD Type 2, we preserve the old version and insert a new one. Our Prep table, main.prep.customers, will contain:




We use the following technical columns:

  • valid_from: Start of the record's validity.

  • valid_to: End of the record's validity.

  • is_current: Indicates the active version.

  • record_hash: Helps identify changes in tracked business attributes.


The processing logic compares incoming records with the current version in Prep. When tracked attributes change, the existing version is expired and a new version is inserted.

The result is a complete historical view of customer data.


How CDF and SCD Type 2 work together

CDF and SCD Type 2 solve different problems. Change Data Feed identifies which rows have changed in a Delta table.  SCD Type 2 determines how business history should be maintained.


In our architecture, the flow is:

  1. New files arrive in Raw.

  2. An ingestion job appends their records to Base.

  3. Delta CDF exposes the new records.

  4. A preparation job reads the changes incrementally.

  5. The incoming records are validated and compared with current customer records.

  6. SCD Type 2 expires old versions and inserts new versions.


We also maintain a durable processing checkpoint so that the CDF consumer knows which Delta version it has already processed. This is important for reliable incremental processing and recovery after job failures. CDF itself is not a permanent archive. Its availability is subject to Delta table retention and vacuum operations. If long-term change-event retention is required, we should persist the events in a separate Delta table.


Gold – Business-ready data

The Gold layer contains data models designed for consumption by reporting tools, dashboards, and analytical workloads.  For example:


main.gold.dim_customer
main.gold.fact_exchange_rates


We can create a current customer view:

CREATE OR REPLACE VIEW main.gold.dim_customer AS
SELECT *
FROM main.prep.customers
WHERE is_current = true;



This gives consumers a straightforward view of the current customer state.  Other Gold models can use the historical records in Prep to perform time-based analysis, such as customer segmentation or historical reporting.


7. Orchestrating the pipeline with Databricks Jobs and Asset Bundles

We'll use separate Databricks Jobs for each major stage:


Databricks Asset Bundles (DAB) allow us to define and deploy these jobs from a local development environment, such as Visual Studio Code. This keeps the project version-controlled and makes deployment repeatable across development and production environments.


Why this architecture?

This architecture provides several benefits:

  • Separation of responsibilities  : Each layer has a clear purpose, making the solution easier to understand and maintain.
  • Reprocessing :  Original files remain available in Raw, allowing us to replay ingestion or correct transformation logic.
  • Incremental processing : CDF avoids repeatedly processing the entire Base table when only a small number of records have changed.
  • Historical tracking : SCD Type 2 preserves previous versions of customer data instead of simply overwriting them.
  • Data governance :Unity Catalog provides centralized governance for tables, schemas, volumes, and access permissions.
  • Extensibility : The same ingestion framework can support CSV files, REST APIs, and additional source systems.


Conclusion

By combining Unity Catalog Volumes, Delta Lake, Change Data Feed, and SCD Type 2, we can build a practical and extensible data platform. The Raw layer preserves the original input, Base provides a reliable Delta ingestion layer, Prep manages data quality and historical changes, and Gold exposes business-ready datasets.


The most important design principle is that each technology has a distinct responsibility:

  • Raw preserves the source.

  • Base ingests the data.

  • CDF tracks Delta changes.

  • Prep validates and historizes the data.

  • SCD Type 2 maintains business history.

  • Gold serves analytical workloads.

This gives us a solid foundation for building more advanced Databricks data pipelines without making the ingestion process and business transformations tightly coupled.


Hennie

Data modelling series : Assertions

Introduction

In data modeling, assertions (also known as business rules or structural assertions) are short, unambiguous sentences written in plain language that define the cardinality between two entities. They serve as a direct translation from a diagram (such as an ERD) into clear agreements with the business.
A well-crafted assertion almost always follows a fixed pattern to capture both minimum (optional vs. mandatory) and maximum (one vs. many) cardinality, and is always read in both directions.


The formula


The Standard Formula for an Assertion : 

A/An [Entity A] [MUST / MAY] [relationship verb] [one / one or more] [Entity B].

MUST = Mandatory (Minimum = 1)
MAY = Optional (Minimum = 0)
one = Maximum = 1
one or more = Maximum = N (many)


Some examples


1. One-to-Many (1:N)  The Most Common Relationship

Scenario: An online store with customers and orders.

Direction 1 (Customer → Order): "A Customer may place one or more Orders." 
Optional, because someone can create an account without buying anything right away: 0..N

Direction 2 (Order → Customer): "An Order must be placed by exactly one Customer." 
Mandatory, an orphaned order without a customer cannot exist: 1..1



2. One-to-One (1:1) – Strict Pairing

Scenario: Employees and their company cars.

Direction 1 (Employee → Company Car): "An Employee may drive at most one Company Car." Optional, not everyone has a company car: 0..1

Direction 2 (Company Car → Employee): "A Company Car must be assigned to exactly one Employee." 
Mandatory, this company does not register unused pool cars: 1..1


3. Many-to-Many (M:N) – Mutual Multiplicity

Scenario: Students and courses at a university.

Direction 1 (Student → Course): "A Student must enroll in one or more Courses." 
Mandatory to maintain active enrollment: 1..N

Direction 2 (Course → Student): "A Course may be attended by one or more Students." 
Optional, a newly created course might still have 0 enrollments: 0..N


Assertions are the ultimate stress test for your data model. When a domain expert reads an assertion and says, "No, that's not how it works in reality" (for example: "An order may also be placed by a guest without an account"), you immediately know you need to adjust your data model and database constraints (NOT NULL vs. NULL) before writing a single line of code.



Hennie


vrijdag 20 november 2026

Data modelling series : Cardinality

Introduction

Data modeling remains essential because it transforms raw data into reliable, usable, and scalable information, regardless of how fast technologies like cloud storage, NoSQL, or AI evolve. Without a solid data model, organizations end up with data chaos : leading to flawed analytics, slow systems, and untrustworthy AI outputs.

 

Reasons

Reasons why data modelling is still important : 

  • Foundation for AI and Machine Learning: AI models and LLMs are only as good as the data feeding them (garbage in, garbage out). A clear data model provides context, clean relationships, and consistent definitions, enabling AI systems to make accurate predictions and hallucinate less.
  • Single Source of Truth: Within a company, terms like "active customer" or "revenue" often mean different things to marketing than they do to finance. Data modeling forces organizations to agree on and enforce clear business rules and definitions before building reports or dashboards.
  • Preventing High Cloud Costs and Technical Debt: Modern cloud data platforms (such as Snowflake or BigQuery) make it easy to dump massive amounts of unstructured data. However, without a proper model, complex queries become painfully slow and cloud compute costs skyrocket.
  • Data Governance and Privacy Compliance (GDPR): Privacy laws and security standards require organizations to know exactly what personal data they hold, where it lives, and how it connects. A data model makes data lineage and access control transparent and auditable.
  • Bridge Between Business and IT: A data model (especially at the conceptual and logical levels) acts as a shared language. It aligns domain experts and software engineers on business processes and expectations before a single line of code is written.


Cardinality

In this blogpost I want to go more in depth about cardinality between entities. Below an example of a Customer, order and product. It's not a perfect example but assume it is ;-). I borrowed this example from a youtube video from Lucidchart.



We have a minimum and maximum number that an entity instance(s) can have related to another entitiy instance(s). Lets understand the maximum and minimum cardinality.


Maximum cardinality rules :

  • One-to-One (1:1): One instance of Entity A connects to at most one instance of Entity B, and vice versa (e.g., a person and a passport). 
  • One-to-Many (1:N) / Many-to-One (N:1): One instance of A connects to many instances of B, while each instance of B connects to at most one instance of A (e.g., one customer places many orders).
  • Many-to-Many (M:N): Multiple instances of A connect to multiple instances of B and vice versa (e.g., students and courses). We also call this in datamodelling an associative entity.

Minimum cardinality (optionality) rules :

  • Mandatory (Minimum = 1): An entity instance must participate in the relationship.
  • Optional (Minimum = 0): An entity instance may participate without a matching record on the other side (e.g., a customer may have 0 orders). 

There is a difference between : and .. . If you say it is 1:N then we reason from maximum cardinality and if we say 0..N. Use a double dot (..) when defining the exact rules for one specific direction (minimum..maximum). 


How they fit together? Take a standard One-to-Many (1:N) relationship between a Customer and an Order:
  • Overall (maximum) relationship: 1:N (Customer to Orders).
  • Customer → Order (0..N): "A Customer may place zero, one, or many Orders."
  • Order → Customer (1..1): "An Order must belong to one and only one Customer."

So it's a bit confusing, when we say a relation is 1:N, because this the MAXIMUM relationship, and this gives only a specific view of the reality. 






So we have four options :




Now let's investigate this in more depth. So what does this mean? How many combinations can we create? As it seems we can create 10 combinations.





One to one (3 variants)

In a One-to-One relationship, a single record in Entity A links to at most one record in Entity B, and vice versa. Here are the variants with examples:





Why It Matters: 1:1 relationships are often used to separate sensitive data (like user credentials or medical records) from general profile data for security and performance.


One to many (4 variants)

The One-to-Many relationship is the most common building block in relational databases. One record in the "parent" entity can link to multiple records in the "child" entity, while each child record belongs to only one parent.



Why It Matters: Getting the direction of 1:N right prevents catastrophic reporting bugs : such as accidentally multiplying revenue numbers when joining customer and order tables in BI dashboards.

Many to Many (3 variants)

In a Many-to-Many relationship, multiple records in Entity A can link to multiple records in Entity B, and vice versa.



Why It Matters: N:M relations are often used in conceptual modelling. Relational databases cannot store a direct M:N link cleanly without duplicating data. To solve this, data modelers introduce a bridge table (such as Enrollment), splitting one M:N relationship into two clean 1:N relationships.

Hennie