Data quality assertions in Apache Spark - Time & Space Complexity
We want to understand how the time needed to check data quality changes as the data grows.
How does the number of checks grow when we have more data rows?
Analyze the time complexity of the following code snippet.
from pyspark.sql.functions import col
def assert_no_nulls(df, column_name):
null_count = df.filter(col(column_name).isNull()).count()
assert null_count == 0, f"Null values found in {column_name}"
# Example usage
assert_no_nulls(dataframe, "age")
This code checks if a specific column in a Spark DataFrame has any null values by filtering and counting them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Filtering rows to find null values in one column.
- How many times: The filter operation scans all rows once.
The time to check grows roughly in direct proportion to the number of rows because each row is checked once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: Doubling the data roughly doubles the work needed to check for nulls.
Time Complexity: O(n)
This means the time to check data quality grows linearly with the number of rows.
[X] Wrong: "Checking for nulls is instant no matter how big the data is."
[OK] Correct: The system must look at each row to find nulls, so more rows mean more work.
Understanding how data quality checks scale helps you design efficient data pipelines and shows you know how to handle growing data.
"What if we check multiple columns for nulls in one pass? How would the time complexity change?"
Practice
Solution
Step 1: Understand data quality assertions
Data quality assertions are used to verify if data follows expected rules and to detect errors like missing or invalid values.Step 2: Compare with other options
Options B, C, and D describe other Spark tasks unrelated to data quality assertions.Final Answer:
To check if data meets expected rules and find errors -> Option CQuick Check:
Data quality assertions = check rules and errors [OK]
- Confusing assertions with performance optimizations
- Thinking assertions create new data columns
- Mixing assertions with visualization tasks
age has no null values?Solution
Step 1: Understand null checking in Spark
To check for nulls, useisNull(). Counting rows whereageis null should be zero for no nulls.Step 2: Analyze each option
df.filter(df.age.isNull()).count() == 0 correctly checks if count of nullageis zero. df.filter(df.age.isNotNull()).count() == 0 checks for non-null count equals zero, which is wrong. Options C and D usenullwith == or != which is invalid in Spark.Final Answer:
df.filter(df.age.isNull()).count() == 0 -> Option AQuick Check:
Use isNull() to find nulls, count should be zero [OK]
- Using == null instead of isNull()
- Checking isNotNull() count equals zero
- Confusing null checks with non-null checks
from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() data = [(1, 'Alice', 25), (2, 'Bob', None), (3, 'Charlie', 30)] df = spark.createDataFrame(data, ['id', 'name', 'age']) null_count = df.filter(df.age.isNull()).count() print(null_count)
Solution
Step 1: Identify null values in the data
The data has one row whereageis None (null): the second row with Bob.Step 2: Count rows with null age
The filterdf.age.isNull()selects rows with null age, so count will be 1.Final Answer:
1 -> Option BQuick Check:
One null age value = 1 [OK]
- Counting non-null rows instead of null rows
- Misreading None as a valid age
- Assuming no nulls without checking
salary are positive:
assert df.filter(df.salary <= 0).count() == 0But it passes even when there are null values in the salary column. What is the likely cause?
Solution
Step 1: Understand filter behavior with nulls
In Spark,null <= 0evaluates to null, which is falsy infilter(), so null rows are skipped and not counted, causing the assertion to pass incorrectly when nulls exist.Step 2: Eliminate other options
A: <= is valid in Spark filters. C:count()is supported on DataFrames. D:assertsyntax is correct. B identifies the null-skipping issue.Final Answer:
The columnsalarycontains null values, which are skipped by the comparison -> Option AQuick Check:
Nulls skipped in comparison filters [OK]
- Not realizing nulls are skipped in comparison filters
- Thinking comparisons catch nulls as invalid
- Blaming syntax instead of null handling
df has no duplicate user_id values. Which Spark code correctly performs this data quality assertion?Solution
Step 1: Understand duplicate detection logic
Duplicates mean someuser_idappear more than once. Grouping byuser_idand counting, then filtering counts > 1 finds duplicates.Step 2: Analyze each option
A:df.dropDuplicates().count() == df.count()checks for completely identical rows across all columns, missing duplicates inuser_idwith differing other columns. B:df.select('user_id').count() == df.count()always true. C: Checks only nulls. D: Correctly finds groups with count > 1.Final Answer:
assert df.groupBy('user_id').count().filter('count > 1').count() == 0 -> Option DQuick Check:
Group and filter counts > 1 to find duplicates [OK]
- Using dropDuplicates() without column subset
- Using count() without distinct or groupBy
- Confusing null checks with duplicate checks
Ready to prove it?
Pass the test and this pattern moves unknown
