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.


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