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.