Implement a strategy to automate data quality checks and validation using PySpark for a data lake.
Instruction: Outline the framework or approach you would use to ensure data integrity and quality.
Updated
Treat validation as a versioned contract evaluated before a new data-lake version becomes available to consumers. Define required fields, keys, ranges, reference integrity, freshness and expected volume with the data owner. Keep the source version, rule version, run ID and rejected rows so a failed batch can be investigated and replayed.
For an existing session named spark, this complete fixture measures ID completeness and duplicate excess separately:
from pyspark.sql import functions as F
def id_quality(df):
row = df.agg(
F.count('*').alias('rows'),
F.count('id').alias('non_null_ids'),
F.countDistinct('id').alias('distinct_ids'),
).first()
n, present, distinct = row.rows, row.non_null_ids, row.distinct_ids
return {
'rows': n,
'id_completeness': present / n if n else None,
'duplicate_excess': present - distinct,
}
data = spark.createDataFrame([(1,), (1,), (None,), (2,)], 'id long')
assert id_quality(data) == {
'rows': 4, 'id_completeness': 0.75, 'duplicate_excess': 1
}
assert id_quality(data.limit(0))['id_completeness'] is None
Duplicate excess counts occurrences beyond the first non-null occurrence of each ID; it is not the number of rows belonging to duplicate groups. An empty dataset has an undefined completeness ratio and needs a separate expected-volume decision. A 100% non-null field can still contain invalid or fabricated values.
Automate these checks after ingestion, before publication. Separate hard failures from warnings, retain row-level reason flags, and reconcile accepted plus quarantined rows against the input. On a hard failure, keep the prior good published version and alert the responsible owner with aggregate evidence, not sensitive raw records. Make retry publication idempotent and use the storage/table system's supported atomic commit mechanism. Test deliberately corrupted, duplicated, empty and late batches; monitoring successful job completion alone does not establish data quality.