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 :
- Databricks series : Starting a new python project in Visual Studio Code (Part I)
- Databricks series : setting up a connection to Databricks from local IDE (Part II)
- Databricks series : Setting up a Databricks project in Visual Studio Code (part III)
- Databricks series : Deployment from Visual Studio Code (Part IV)
- Databricks series : Execute the job in Databricks (Part V)
- Databricks series : A configrable framework in Databricks (Part VI)
- Databricks series : Loading strategies in Databricks (Part VII)
- Databricks series : Data contracts in Databricks (Part VIII)
- Databricks series : Debugging Python code in Visual Studio Code with arguments (Part IX)
- Databricks series : ODCS Data contracts in Databricks (Part X)
- Databricks series : reading an API (Part XI)
- Databricks series : Building a mediallion architecture with SCD Type 2 (step 1)(Part XII)
- Databricks series : Building a mediallion architecture with SCD Type 2 (step 2) (Part XIII)
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
/Volumes/main/raw/files/customers.csv /Volumes/main/raw/files/customers_update.csv
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" )
display( dbutils.fs.ls( "/Volumes/main/raw/files/customers/" ) )
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
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?
Reads the CSV file from Raw.
Adds technical metadata.
Generates a unique batch ID.
Creates the Base Delta table on the first run.
Appends records on subsequent runs.
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)
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
databricks bundle deploy -t dev
Execute the initial ingestion
Run the first job:
databricks bundle run transfer_job -t dev --params entity=customers_base
customers.csv and creates:main.base.customers
databricks bundle run transfer_job -t dev --params entity=customers_update_base
Check the Base table
Open Databricks SQL Editor and run:
SELECT * FROM main.base.customers ORDER BY customer_id;
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;
Verify Change Data Feed
Finally, check whether CDF is enabled:
SHOW TBLPROPERTIES main.base.customers;
delta.enableChangeDataFeed = true
You can also inspect the Delta table history:
DESCRIBE HISTORY main.base.customers;
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