vrijdag 27 november 2026

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

Geen opmerkingen:

Een reactie posten