We are going to design a data lakehouse ingestion pipeline that includes:
Schema-on-write: We enforce schema at write time, meaning that when data is ingested, it must conform to a predefined schema.
Quality checks: We will define and enforce data quality constraints (e.g., non-null, uniqueness, referential integrity, etc.) on the ingested data.
Lineage: We will track the lineage of the data (i.e., where the data came from, what transformations were applied, and where it went).
We assume we are using a modern data stack that includes:
A cloud storage (like S3, ADLS, GCS) for the data lake.
A table format (like Delta Lake, Apache Iceberg, or Apache Hudi) for the lakehouse.
A workflow orchestrator (like Apache Airflow, Prefect, or Dagster) for scheduling.
A data quality framework (like Great Expectations, Deequ, or custom checks).
Steps:
Schema-on-write:
We define a schema for each table (or dataset) that we expect to ingest.
When data is written (in batch or streaming), we validate that the data conforms to the schema.
If using Delta Lake, we can use the DeltaTable API to enforce schema at write time (by setting mergeSchema or overwriteSchema appropriately, but note: schema enforcement is default in Delta).
Alternatively, we can do schema validation before writing and then write only if valid.
Quality checks:
We define a set of expectations for each table (e.g., column X must be non-null, column Y must be unique, etc.).
We can run these checks on the ingested data before it is written (or after, but then we might have bad data in the system).
We can use Great Expectations or similar to define and run these checks.
If the checks fail, we can either:
a) Reject the entire batch and alert.
b) Quarantine the bad records and write only the good ones (with a record of the bad ones for review).
Lineage:
We want to capture:
The source of the data (e.g., database, table, file path, timestamp).
The ingestion job (script, DAG, etc.) that processed the data.
The target table and any transformations applied.
We can store lineage in a separate metadata store (like a database table) or use a built-in feature of our table format (e.g., Delta Lake's DESCRIBE HISTORY for table-level lineage, but that doesn't capture column-level or transformation details).
We might need to design a custom lineage table that records:
job_id, source, target_table, transformations, run_timestamp, status, record_count, etc.
Implementation:
We'll design a modular pipeline that can be scheduled (or triggered) to run ingestion for a given source.
Steps in the pipeline:
a) Extract: Read data from the source (could be a database, file, stream, etc.)
b) Validate schema: Check that the incoming data matches the expected schema. If not, fail or handle accordingly.
c) Quality checks: Run the defined quality checks on the extracted data.
d) If both schema and quality checks pass, then write to the lakehouse table (with schema enforcement again at write time, but we already validated).
e) Record lineage: Insert a record into the lineage table with details of this run.
We can also consider:
Idempotency: The same data might be ingested multiple times? We might need to handle duplicates (maybe by using a unique key and upserting).
Partial failures: If a batch fails, we might want to retry or handle the failure.
Example with Delta Lake and Great Expectations:
Let's assume we are using:
Delta Lake for the table format.
Great Expectations for data quality.
Apache Airflow for orchestration.
Steps in an Airflow DAG:
task1 = extract_from_source()
task2 = validate_schema(task1) # This could be a Python function that checks the schema of the DataFrame.
task3 = run_quality_checks(task2) # This uses Great Expectations to run the suite.
task4 = write_to_delta(task3) # Write to Delta table, with schema enforcement.
task5 = record_lineage(task4) # Record lineage.
However, note that Delta Lake already enforces schema at write time. So if we try to write data that doesn't match the schema, it will fail (unless we set mergeSchema to true, which we don't want for schema-on-write). So we can rely on Delta's schema enforcement as a second line of defense, but we also want to validate before writing to avoid writing partial data.
Alternatively, we can write to a staging table and then merge into the target table, but that's more for upserts.
Let's design a more detailed flow for a batch ingestion:
For each source table:
Extract: Read the source data (could be a full snapshot or incremental). We assume we get a DataFrame (Spark, Pandas, etc.)
Pre-write validation:
a) Schema validation: Compare the DataFrame's schema with the expected schema. We can do this by:
- Checking column names and data types.
- We might allow additional columns? (Depends on the business rule.) If we are strict, then the DataFrame must have exactly the same columns (or a subset if we are doing column pruning). But note: Delta Lake's schema enforcement will fail if there are extra columns unless we set mergeSchema to true. So we might want to drop extra columns or fail.
b) Data quality validation: Run the Great Expectations suite. This can produce a report and a list of failed expectations.
If validation passes, write to the target Delta table. We can write in append mode (for new data) or overwrite (for full refresh). We must be cautious with overwrites because we lose history.
After successful write, record lineage.
If validation fails, we can:
Send an alert (email, Slack, etc.)
Save the bad data to a quarantine location (like a separate directory in the data lake) for investigation.
Do not write to the target table.
Lineage design:
We create a table (in a separate metadata database, or in the lakehouse itself) called data_lineage with columns:
code
id: primary key
job_id: the ID of the Airflow DAG run (or similar)
source_name: name of the source (e.g., 'postgres_db.table_name')
source_path: if it's a file, the path; if it's a database, the connection string and query?
target_table: the Delta table we wrote to (including the path or catalog name)
transformation: a string describing the transformations (or JSON if complex). Could be the name of the transformation script.
record_count: number of records written
status: 'success' or 'failed'
run_timestamp: when the job ran
error_message: if failed, the error message
We can also capture more details like:
- The schema of the source and target? (But we can get that from the table definitions.)
- The specific rows that failed? (But that might be too much. We can log the number of failed rows for each check.)
Alternatively, we can use a dedicated lineage tool (like OpenLineage) and send events to a collector.
Implementation details for schema validation:
We can use the pyspark.sql.types to define the expected schema and then compare with the DataFrame's schema.
Example:
code
expected_schema = StructType([
StructField("id", IntegerType(), False),
StructField("name", StringType(), True),
...
])
# Then compare with df.schema
But note: the DataFrame might have extra columns. We can either:
- Fail if there are extra columns (strict mode).
- Select only the columns in the expected schema and ignore extra ones (but then we are altering the data without recording it?).
We might want to be strict and fail if there are extra columns because that indicates a change in the source that we haven't accounted for.
However, sometimes the source might add new columns and we want to ignore them until we update our pipeline. So we can have a configuration:
code
schema_validation_mode = 'strict' # or 'allow_extra_columns'
In allow_extra_columns, we would select only the columns in the expected schema and drop the rest. But then we must record that we dropped columns? That would be a transformation.
So maybe we do:
code
If mode is strict:
Check that the set of columns in df exactly matches the set in expected_schema (and data types match).
If mode is allow_extra_columns:
Check that expected_schema is a subset of df.schema (and data types for the common columns match).
Then, we can do: df = df.select(*expected_schema.fieldNames())
But note: data types might be more general (e.g., source has Long and we expect Integer). We might need to cast? That's another transformation.
So it's complex. We might decide to let Delta Lake handle the schema enforcement and just let it fail if there's a mismatch. But then we don't get a chance to quarantine the bad data.
Alternatively, we can write to a staging table with a different schema (or without schema enforcement) and then run a merge into the target table that does the necessary transformations and schema alignment.
Given the complexity, for simplicity we might:
code
Code structure:
We'll write a Python function (or a set of functions) that can be called from Airflow.
Let's assume we are using Spark.
Steps:
code
def ingest_source(source_config, target_table, quality_suite_path):
# source_config: contains source connection details, query or file path, etc.
# target_table: the Delta table path or name.
# quality_suite_path: path to the Great Expectations suite.
# 1. Extract
df = extract(source_config) # returns a Spark DataFrame
# 2. Validate schema: we load the target table's schema and compare.
target_schema = get_delta_table_schema(target_table) # returns a StructType
# Compare df.schema and target_schema.
# We'll write a function to compare two StructTypes.
if not schemas_match(df.schema, target_schema):
raise SchemaValidationError(f"Schema mismatch. Expected: {target_schema}, Got: {df.schema}")
# 3. Run quality checks with Great Expectations.
# We assume we have a Great Expectations suite defined for the target_table.
# We run the suite on the DataFrame.
results = run_great_expectations(df, quality_suite_path)
if not results['success']:
# We can get the failing expectations and log them.
failing_expectations = [exp for exp in results['results'] if not exp['success']]
raise DataQualityError(f"Data quality checks failed: {failing_expectations}")
# 4. Write to Delta table.
df.write.format("delta").mode("append").save(target_table)
# 5. Record lineage.
record_lineage(
job_id=context['job_id'], # we can get from Airflow context
source_name=source_config['name'],
source_path=source_config['path'],
target_table=target_table,
transformation='direct_copy', # or more if we have transformations
record_count=df.count(),
status='success'
)
Error handling:
We want to catch exceptions and record the lineage with status 'failed' and the error message.
So we wrap the main logic in a try-except.
Also, we want to quarantine the data if validation fails? We can save the DataFrame to a quarantine location (like a separate directory in the data lake) with the error.
Let's adjust:
code
try:
... steps 1-4 ...
except Exception as e:
# Record lineage with failure
record_lineage(..., status='failed', error_message=str(e))
# Optionally, save the bad data to quarantine
quarantine_path = f"quarantine/{target_table}/{datetime.now().isoformat()}"
df.write.parquet(quarantine_path) # or in delta format? Maybe we don't want to use Delta for quarantine.
raise # or just return? We might not want to fail the DAG if we are quarantining? But probably we want to fail so that we are alerted.
Conclusion:
We have designed a simple batch ingestion pipeline that:
code
- Validates schema against the target table's schema.
- Runs Great Expectations data quality checks.
- Writes to a Delta table (if valid) in append mode.
- Records lineage in a separate table.
- Quarantines bad data and records lineage on failure.
This is a starting point. In reality, we would need to handle:
code
- Incremental loads and upserts.
- More complex transformations.
- Streaming ingestion.
- Partitioning and optimization of the Delta table.
- More robust error handling and retries.
- Monitoring and alerting.
But for the purpose of this question, we have outlined the key components.
Additional note:
The schema validation function schemas_match must be implemented. We can compare:
code
- Number of fields.
- Field names (order might not matter? In Spark, order matters? Actually, when writing to a table, the order of columns in the DataFrame must match the table? I think it does matter. But we can reorder the DataFrame to match the table's column order.)
So we might want to reorder the DataFrame columns to match the target table's column order.
Alternatively, we can let the write fail if the column order is wrong? Actually, when writing to a Delta table, Spark will match by column name, not by position. So order doesn't matter? I think for Delta Lake, it does not require the same order. It matches by column name.
But for our own validation, we might not care about order. We just want to make sure all required columns are present and with the right data types.
So we can do:
code
target_fields = {field.name: field.dataType for field in target_schema.fields}
df_fields = {field.name: field.dataType for field in df.schema.fields}
# Check that all target fields are in df_fields and with the same data type.
for name, dtype in target_fields.items():
if name not in df_fields:
raise SchemaValidationError(f"Missing column: {name}")
if df_fields[name] != dtype:
raise SchemaValidationError(f"Data type mismatch for column {name}. Expected: {dtype}, Got: {df_fields[name]}")
# Also, if we don't allow extra columns, then check that df_fields is a subset of target_fields? Actually, we want df to have exactly the same columns as target? Or at least the required ones.
If we are strict, then we also check that df_fields has no extra columns.
But note: the target table might have columns that are not in the DataFrame because they have default values? Actually, when we write a DataFrame to a Delta table, if the DataFrame is missing a column that the table has, then that column will be set to null for the new rows. But if the table column is NOT NULL, then the write will fail.
Final plan for schema validation:
Step 1: Get the target table's schema (from the Delta table).
Step 2: Reorder the DataFrame's columns to match the target table's column order, and only keep the columns that are in the target table.
Step 3: Compare the two schemas (field names, data types, and nullability). If they match, then proceed. Otherwise, fail.
Code for step 3:
code
def schemas_match(df_schema, target_schema):
if len(df_schema.fields) != len(target_schema.fields):
return False
for df_field, target_field in zip(df_schema.fields, target_schema.fields):
if df_field.name != target_field.name:
return False
if df_field.dataType != target_field.dataType:
return False
if df_field.nullable != target_field.nullable:
return False
return True
But note: the order of fields in the DataFrame after select might not be the same as in the target_schema? We selected in the order of target_columns, so it should be.
Putting it all together:
We assume we have:
code
- A Delta table already created with the desired schema.
- A Great Expectations suite for that table.
The ingestion function:
code
def ingest_source(source_config, target_table, quality_suite_path, schema_mode='strict'):
# Extract
df = extract(source_config)
# Get target schema
target_schema = get_delta_table_schema(target_table)
# Reorder and select columns to match target
target_columns = [field.name for field in target_schema.fields]
df = df.select(*target_columns)
# Validate schema
if not schemas_match(df.schema, target_schema):
raise SchemaValidationError(f"Schema does not match target table {target_table}")
# Run quality checks
results = run_great_expectations(df, quality_suite_path)
if not results['success']:
failing = [exp for exp in results['results'] if not exp['success']]
raise DataQualityError(f"Data quality checks failed: {failing}")
# Write
df.write.format("delta").mode("append").save(target_table)
# Record lineage (success)
But note: what if the source doesn't have all the columns? Then the select will fail because the column doesn't exist. So we must make sure that the source has at least all the columns that the target table has.
Alternatively, we can do:
code
available_columns = [col for col in target_columns if col in df.columns]
missing_columns = set(target_columns) - set(available_columns)
if missing_columns:
raise SchemaValidationError(f"Source data missing columns: {missing_columns}")
df = df.select(*available_columns)
Then we compare the schema? But then we are missing some columns. So we must have all columns.
Conclusion:
This is a basic design. In reality, we might need to handle more complex scenarios.
We have:
code
- Schema-on-write: by validating against the target schema and then writing to Delta (which also enforces schema).
- Quality checks: using Great Expectations.
- Lineage: by recording in a separate table.
We also quarantine on failure.
We assume full snapshot and append mode.
This is a starting point for a data lakehouse ingestion pipeline.
Note on lineage:
We record lineage in a table. We can create this table in the same Delta Lake or in a separate database.
Example lineage table schema (in SQL):
code
CREATE TABLE data_lineage (
id BIGINT GENERATED BY DEFAULT AS IDENTITY,
job_id STRING,
source_name STRING,
source_path STRING,
target_table STRING,
transformation STRING,
record_count BIGINT,
status STRING, -- 'success' or 'failed'
run_timestamp TIMESTAMP,
error_message STRING,
PRIMARY KEY (id)
);
We can also use Delta Lake for this table.
We insert a record at the beginning of the pipeline (with status 'running') and update at the end? Or insert at the end with the final status.
We can do:
code
At the start: insert a record with status 'running', and then at the end update it? Or we can insert at the end with the final status.
But if the pipeline fails, we want to record the failure. So we can:
code
try:
insert lineage record with status 'running' (optional)
... do work ...
update lineage record to 'success'? or insert at the end?
except:
insert lineage record with status 'failed'
Alternatively, we can insert at the beginning with status 'running' and then update at the end. But if the pipeline fails before the insert, we don't have a record. So we might want to insert at the beginning and then update.
Let's do:
code
lineage_id = insert_lineage_record(job_id, source_name, source_path, target_table, transformation, status='running', run_timestamp=now)
Then in the try block, do the work and then update the record to success and set record_count.
In the except block, update the record to failed and set error_message.
Final code structure:
def ingest_source(source_config, target_table, quality_suite_path, transformation='direct_copy'):
job_id = generate_job_id() # or get from Airflow context
try:
# Extract
df = extract(source_config)
code
# Get target schema and reorder/select columns
target_schema = get_delta_table_schema(target_table)
target_columns = [field.name for field in target_schema.fields]
missing = set(target_columns) - set(df.columns)
if missing:
raise SchemaValidationError(f"Missing columns: {missing}")
df = df.select(*target_columns)
# Validate schema (now that we have the same columns in the same order, check data types and nullability)
if not schemas_match(df.schema, target_schema):
raise SchemaValidationError(f"Schema mismatch. Expected: {target_schema}, Got: {df.schema}")
# Quality checks
results = run_great_expectations(df, quality_suite_path)
if not results['success']:
failing = [exp for exp in results['results'] if not exp['success']]
raise DataQualityError(f"Data quality checks failed: {failing}")
# Write
record_count = df.count()
df.write.format("delta").mode("append").save(target_table)
# Record lineage (success)
record_lineage(
job_id=job_id,
source_name=source_config['name'],
source_path=source_config['path'],
target_table=target_table,
transformation=transformation,
record_count=record_count,
status='success',
run_timestamp=datetime.now()
)
except Exception as e:
# Record lineage (failed)
record_lineage(
job_id=job_id,
source_name=source_config['name'],
source_path=source_config['path'],
target_table=target_table,
transformation=transformation,
record_count=0, # or we can try to get the count of the DataFrame? But it might be partially processed?
status='failed',
run_timestamp=datetime.now(),
error_message=str(e)
)
# Quarantine the data if available
if 'df' in locals():
quarantine_path = f"quarantine/{target_table}/{datetime.now().isoformat()}"
df.write.parquet(quarantine_path)
raise
Implementation of helper functions:
extract: depends on the source. Could be reading from a database using JDBC, or from a file.
get_delta_table_schema: we can use spark.read.format("delta").load(target_table).schema but note: if the table doesn't exist, we might need to create it? We assume it exists.
Alternatively, we can get the schema from the Delta table's metadata without reading the data:
But note: toDF() will read the data? Actually, it returns a DataFrame with the schema. It doesn't read the data until we do an action.
So it's safe.
run_great_expectations: we need to set up a Great Expectations context and run a suite. We assume the suite is stored in a directory and we can load it.
Example:
code
import great_expectations as ge
context = ge.data_context.DataContext(context_root_dir=...)
batch = ge.dataset.SparkDFDataset(df)
results = context.run_validation_operator(
"action_list_operator",
assets_to_validate=[batch],
validation_operator_name=... # or use a suite name?
)
But we have a suite for the table. We can do:
code
suite = context.get_expectation_suite(quality_suite_path) # or by name?
batch = ge.dataset.SparkDFDataset(df)
results = batch.validate(suite)
We need to check the Great Expectations documentation for the exact way.
record_lineage: we can use spark to write to a Delta table for lineage.
But note: we are in an except block and we might not have a Spark session? We do, because we used it for the DataFrame.
Limitations:
We are only handling batch, full snapshot.
We are not handling incremental updates or upserts.
We assume the target Delta table already exists.
We assume the source is a single file or database query that returns a DataFrame.
We are not handling schema evolution (like adding new columns to the target table). We would have to update the pipeline.
But this is a starting point.
Conclusion:
We have designed a data lakehouse ingestion pipeline with schema-on-write, quality checks, and lineage.
The code above is a sketch. In practice, we would need to adjust for the specific use case.
We also need to consider:
code
- How to handle very large tables? Counting might be expensive. We might skip the count for lineage? Or use the count from the write operation? Actually, when we write in append mode, we don't get the count. We can use `df.write` with `option("recordCount", ...)`? No, that's for the number of records per file.
We can do:
df.write.format("delta").mode("append").save(target_table)
# Then we can get the latest count from the table? But that would be the total count, not the count of this batch.
So we have to count the batch. Alternatively, we can avoid counting and just record that we wrote some data? But for monitoring, we want to know how many rows we wrote.
We can use `df.count()` and then write. It's an extra pass, but for monitoring it's acceptable.
We are writing the entire batch at once. For very large batches, we might want to write in partitions? But df.write will handle that.
We are not optimizing the Delta table (like vacuum, optimize) after write. That can be a separate step.
We are not handling errors in the lineage recording. If that fails, we might lose lineage. We can try to write lineage in a separate try-except and log if it fails.
Given the complexity, we might break the lineage recording into a separate step that is idempotent and can be retried.
But for simplicity, we do it in the same function.
Final note:
This is a high-level design. The actual implementation would depend on the specific technologies and requirements.
We have provided a conceptual solution that can be adapted.
Let me know if you have any questions or need more details on a specific part.
I'll design a comprehensive data lakehouse ingestion pipeline with schema-on-write enforcement, data quality checks, and lineage tracking. Below is a production-ready architecture using modern open-source technologies.
from pyspark.sql.types import *
from delta.tables import DeltaTable
class SchemaEnforcer:
def __init__(self, schema_config):
self.schema = StructType.fromJson(schema_config["schema"])
self.table_name = schema_config["table_name"]
def enforce_schema(self, df):
"""Validate and enforce schema on write"""
# 1. Check column existence
missing_cols = set([f.name for f in self.schema.fields]) - set(df.columns)
extra_cols = set(df.columns) - set([f.name for f in self.schema.fields])
if missing_cols:
raise ValueError(f"Missing columns: {missing_cols}")
# 2. Type validation (strict mode)
for field in self.schema.fields:
if field.name in df.columns:
if not isinstance(df.schema[field.name].dataType, type(field.dataType)):
raise TypeError(f"Column {field.name} type mismatch. "
f"Expected {field.dataType}, "
f"got {df.schema[field.name].dataType}")
# 3. Select only expected columns (drop extras if allowed)
if extra_cols and schema_config.get("strict_mode", True):
raise ValueError(f"Extra columns found: {extra_cols}")
return df.select([f.name for f in self.schema.fields])
Implement data catalog integration (AWS Glue/Unity Catalog)
Would you like me to elaborate on any specific component or provide implementation for a particular cloud platform?
- Define the expected schema as the target schema.
- Before writing, we try to cast the DataFrame to the expected schema (or let Spark do it automatically when writing?).
In Delta Lake, if we write a DataFrame with a schema that doesn't match the target table, it will fail unless we set mergeSchema to true. So we can set mergeSchema to false and then we are safe: only data that matches the target schema will be written. But note: if the DataFrame has extra columns, it will fail. So we must make sure the DataFrame has exactly the same columns (or a subset, then the missing columns will be null? Actually, no: if the DataFrame is missing a column that the table has, then that column will be set to null for the new rows? That might be acceptable if the column is nullable. But if the column is non-null, then it will fail because of the non-null constraint? Delta Lake doesn't enforce non-null at the table level by default? Actually, Delta Lake does enforce NOT NULL constraints if they are defined in the table schema.
So, if we have a table with a NOT NULL column and we try to write a DataFrame that doesn't have that column, then the write will fail because the column would be set to null.
Therefore, we must ensure that the DataFrame has all the non-nullable columns of the target table.
Given these complexities, it might be better to do:
code
Step 1: Let the source data be extracted as is.
Step 2: We define a transformation that maps the source data to the target schema. This transformation can:
- Rename columns.
- Cast data types.
- Drop extra columns.
- Add missing columns with default values (or null if nullable).
Step 3: Then we run quality checks on the transformed data (which now matches the target schema).
Step 4: Write to the target table (which should now match the schema exactly).
This way, we are in control of the transformation and we can record it as part of the lineage.
So, we need a configuration that defines the mapping from source to target.
Example:
code
source_columns = ['src_id', 'src_name', 'src_date']
target_columns = ['id', 'name', 'ingestion_date']
transformation_rules = {
'id': 'src_id',
'name': 'src_name',
'ingestion_date': 'current_date()'
}
Then we can build a DataFrame with the target columns by selecting and transforming.
This is getting into the realm of an ELT tool.
Given the scope, we might assume that the source and target schemas are aligned (i.e., same column names and types) and we are just doing a direct copy. Then the only validation is that the source data matches the target schema.
But in reality, we often have to do some transformation.
Let's simplify:
code
We assume that the source data is already in the same format as the target table (or we have a separate transformation step that we have already defined and tested).
Then our pipeline does:
extract -> validate_schema (against target schema) -> quality_checks -> write (to target Delta table) -> record_lineage.
And if the source and target schemas are not aligned, we fail.
But note: the target table might have more columns (with default values) or less? We must decide.
Given the time, we'll design for the simple case and note that in reality we might need a more flexible transformation layer.
However, note: we are writing in append mode. What if we want to do upserts? Then we need to use merge.
We are also not handling incremental loads. We assume full snapshot.
For incremental, we would have a condition on the source (e.g., timestamp > last_run) and then we might need to handle updates and deletes. That's more complex and might require a merge.
Given the complexity, we stick to full snapshot for now.
So we must have all NOT NULL columns in the DataFrame.
Therefore, we should check only for the non-nullable columns? Actually, we are comparing the entire schema. We are also checking data types.
Given the complexity, we might rely on Delta Lake's own schema enforcement and just write. But then we don't get a chance to quarantine.
So we do:
code
We check that the DataFrame has at least all the columns that are in the target table and that the data types are compatible.
But note: the target table might have a column that is nullable and we don't have it in the DataFrame -> that's okay (it will be set to null). But if the column is non-nullable, then we must have it.
So we should check:
code
for field in target_schema.fields:
if field.name not in df_fields and not field.nullable:
raise SchemaValidationError(f"Missing non-nullable column: {field.name}")
if field.name in df_fields and df_fields[field.name] != field.dataType:
# But we might allow implicit casting? For example, Integer to Long?
# We can check if the DataFrame's data type is a subtype of the target's?
# This is getting too complex.
Given time, we might just do:
code
We require that the DataFrame has the same column names and data types as the target table, and we don't allow extra columns.
But in practice, we might want to allow the DataFrame to have extra columns and then drop them? That would be a transformation.
So we decide:
code
We will only validate the columns that are in the target table. We don't care about extra columns in the DataFrame? But then when we write, Delta Lake will fail if there are extra columns (unless we set mergeSchema). So we must drop extra columns.
Therefore, we do:
code
# Select only the columns that are in the target table and in the same order as the target table.
target_columns = [field.name for field in target_schema.fields]
df = df.select(*target_columns)
Then we compare the schema of this new df with the target_schema. They should be exactly the same.
But note: the data types might not match exactly (e.g., source has Long, target has Integer). We might need to cast.
So we might need to do:
code
for field in target_schema.fields:
if field.name in df.columns:
if df.schema[field.name].dataType != field.dataType:
df = df.withColumn(field.name, df[field.name].cast(field.dataType))
This is getting into the transformation layer.
Given the complexity, we might decide that the source must already match the target schema exactly, and we don't do any casting. Then we just select the columns in the right order and then write.
So:
code
target_columns = [field.name for field in target_schema.fields]
df = df.select(*target_columns)
Then we check that the schema of df matches exactly the target_schema (including data types and nullability). If not, fail.
This is strict but safe.
Therefore, we require that the source has all the columns that the target table has.
But if the insert fails, then we don't have a record. That's acceptable because we want to know that the job failed even before we could record.
Alternatively, we can insert at the end with the final status. Then we don't have a record for running jobs? But we can have a separate monitoring table for running jobs? Not necessary.
We can just insert at the end:
code
if success:
insert_lineage_record(..., status='success', record_count=...)
else:
insert_lineage_record(..., status='failed', error_message=...)
And then we can query the lineage table for the last run of a job by job_id and run_timestamp.
We'll do:
code
At the end of the pipeline (whether success or failure) we insert a record.
So we wrap the entire function in a try-except and then insert accordingly.
Note: We are using df.count() which might be expensive. We can avoid it by using df.count() only for lineage? Or we can get the count from the write operation? Actually, when we write, we don't get the count. So we have to count before writing.
Alternatively, we can write and then count the number of rows written? But if the write fails, we don't have the count.
So we count before writing. This is acceptable for batch.
However, if the error happened before we created the Spark session? Then we don't have a Spark session. But we assume we are in a Spark environment.
# pipelines/ingest_customers.py
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import json
from functools import reduce
class LakehouseIngestionPipeline:
def __init__(self, config_path):
with open(config_path) as f:
self.config = json.load(f)
self.spark = SparkSession.builder \
.appName("LakehouseIngestion") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.getOrCreate()
self.schema_enforcer = SchemaEnforcer(self.config)
self.quality_validator = DataQualityValidator(
self.config["quality_suite"]
)
self.lineage_tracker = LineageTracker()
def extract(self, source_config):
"""Extract from source system"""
if source_config["type"] == "jdbc":
return self.spark.read \
.format("jdbc") \
.option("url", source_config["url"]) \
.option("dbtable", source_config["query"]) \
.option("user", source_config["user"]) \
.option("password", source_config["password"]) \
.load()
elif source_config["type"] == "s3":
return self.spark.read \
.format(source_config["format"]) \
.load(source_config["path"])
# Add more sources as needed
def transform(self, df):
"""Apply business transformations"""
# Add metadata columns
df = df.withColumn("_ingestion_timestamp", current_timestamp()) \
.withColumn("_batch_id", lit(self.batch_id)) \
.withColumn("_source_file", input_file_name())
# Apply transformations from config
for transform in self.config.get("transformations", []):
df = eval(transform) # Caution: Use safe eval in production
return df
def load(self, df, target_table):
"""Write to lakehouse with schema enforcement"""
# Enforce schema
df = self.schema_enforcer.enforce_schema(df)
# Write to Delta table
writer = df.write.format("delta") \
.mode("append") \
.option("mergeSchema", "false") # Strict schema enforcement
# Partition if configured
if "partitioning" in self.config:
writer = writer.partitionBy(*self.config["partitioning"])
writer.save(target_table)
# Optimize table if needed
if self.config.get("optimize_after_write", False):
self.spark.sql(f"OPTIMIZE {target_table}")
def run(self):
"""Execute full pipeline"""
self.batch_id = f"batch_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
# Start lineage tracking
run_id, job = self.lineage_tracker.start_run(
job_name=self.config["pipeline_name"],
source=self.config["source"],
target={"namespace": "delta", "name": self.config["table_name"]},
transformation="ingestion"
)
try:
# Extract
raw_df = self.extract(self.config["source"])
# Transform
transformed_df = self.transform(raw_df)
# Quality checks
validation_result = self.quality_validator.validate(
transformed_df,
self.batch_id
)
# Handle quality results
if validation_result["success"]:
# Load to main table
self.load(transformed_df, self.config["target_table"])
record_count = transformed_df.count()
else:
# Separate good/bad records
good_df, failed_checks = self.quality_validator.check_and_quarantine(
transformed_df,
validation_result
)
self.load(good_df, self.config["target_table"])
record_count = good_df.count()
self._log_quality_issues(failed_checks)
# Complete lineage
self.lineage_tracker.complete_run(
run_id=run_id,
job=job,
record_count=record_count,
transformation="ingestion"
)
# Update metadata table
self._update_pipeline_metadata(
status="SUCCESS",
record_count=record_count,
failed_expectations=[] if validation_result["success"]
else [exp["expectation_type"]
for exp in validation_result["results"]
if not exp["success"]]
)
except Exception as e:
# Failure lineage
self.lineage_tracker.complete_run(
run_id=run_id,
job=job,
record_count=0,
transformation="ingestion_failed"
)
self._update_pipeline_metadata(
status="FAILED",
error_message=str(e)
)
raise
def _update_pipeline_metadata(self, **kwargs):
"""Update metadata table with run details"""
metadata = {
"pipeline_name": self.config["pipeline_name"],
"batch_id": self.batch_id,
"run_timestamp": datetime.utcnow(),
"source": self.config["source"]["name"],
"target_table": self.config["target_table"],
**kwargs
}
metadata_df = self.spark.createDataFrame([metadata])
metadata_df.write.mode("append") \
.save("s3://data-lakehouse/metadata/pipeline_runs/")