Bird
Raised Fist0
Apache Sparkdata~20 mins

Data quality assertions in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Data Quality Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Data Quality Assertion with Null Check
What will be the output of the following Apache Spark code snippet that asserts no null values in the 'age' column?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.appName('Test').getOrCreate()
data = [(1, 'Alice', 25), (2, 'Bob', None), (3, 'Charlie', 30)]
df = spark.createDataFrame(data, ['id', 'name', 'age'])

# Assert no nulls in 'age'
df.select('age').filter(col('age').isNull()).count() == 0
AThrows an exception
BTrue
CFalse
DNone
Attempts:
2 left
💡 Hint
Check if any rows have null in the 'age' column.
❓ data_output
intermediate
2:00remaining
Number of Rows Failing a Data Quality Assertion
Given the following Spark DataFrame, how many rows fail the assertion that 'salary' must be greater than 3000?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.appName('Test').getOrCreate()
data = [(1, 'John', 4000), (2, 'Jane', 2500), (3, 'Doe', 3500), (4, 'Smith', 3000)]
df = spark.createDataFrame(data, ['id', 'name', 'salary'])

failing_rows = df.filter(col('salary') <= 3000).count()
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Count rows where salary is less than or equal to 3000.
🔧 Debug
advanced
2:00remaining
Identify the Error in Data Quality Assertion Code
What error will the following Spark code raise when checking if all 'email' values contain '@'?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.appName('Test').getOrCreate()
data = [(1, 'alice@example.com'), (2, 'bobexample.com')]
df = spark.createDataFrame(data, ['id', 'email'])

# Check if all emails contain '@'
assertion = df.filter(~col('email').contains('@')).count() == 0
print(assertion)
ASyntaxError
BTrue
CFalse
DAttributeError
Attempts:
2 left
💡 Hint
Check if the 'contains' method is valid on a Column object.
❓ visualization
advanced
2:00remaining
Visualizing Data Quality Assertion Failures
Which plot best shows the count of rows failing a data quality assertion that 'score' must be between 0 and 100?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
import matplotlib.pyplot as plt

spark = SparkSession.builder.appName('Test').getOrCreate()
data = [(1, 95), (2, 105), (3, -5), (4, 50)]
df = spark.createDataFrame(data, ['id', 'score'])

fail_df = df.filter((col('score') < 0) | (col('score') > 100))
fail_count = fail_df.count()

# Plot code here
AA line chart showing scores over ids
BA bar chart with one bar labeled 'Failing Rows' showing value 2
CA pie chart with two slices: 'Failing' 2 and 'Passing' 2
DA scatter plot of id vs score
Attempts:
2 left
💡 Hint
Count of failing rows is 2; a bar chart can show this count clearly.
🧠 Conceptual
expert
2:00remaining
Best Practice for Data Quality Assertions in Spark Pipelines
Which option describes the best practice for implementing data quality assertions in Apache Spark ETL pipelines?
ARun assertions after all transformations and before writing data to storage to catch errors early
BRun assertions only once at the very end of the pipeline to minimize performance impact
CSkip assertions and rely on schema validation only to improve speed
DRun assertions before any transformations to validate raw data only
Attempts:
2 left
💡 Hint
Consider when errors should be caught to avoid propagating bad data.

Practice

(1/5)
1. What is the main purpose of data quality assertions in Apache Spark?
easy
A. To create new columns based on calculations
B. To speed up data processing by caching
C. To check if data meets expected rules and find errors
D. To visualize data trends over time

Solution

  1. 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.
  2. Step 2: Compare with other options

    Options B, C, and D describe other Spark tasks unrelated to data quality assertions.
  3. Final Answer:

    To check if data meets expected rules and find errors -> Option C
  4. Quick Check:

    Data quality assertions = check rules and errors [OK]
Hint: Assertions check data rules and errors, not processing speed [OK]
Common Mistakes:
  • Confusing assertions with performance optimizations
  • Thinking assertions create new data columns
  • Mixing assertions with visualization tasks
2. Which of the following is the correct way to assert that a Spark DataFrame column age has no null values?
easy
A. df.filter(df.age.isNull()).count() == 0
B. df.filter(df.age.isNotNull()).count() == 0
C. df.filter(df.age == null).count() == 0
D. df.filter(df.age != null).count() == 0

Solution

  1. Step 1: Understand null checking in Spark

    To check for nulls, use isNull(). Counting rows where age is null should be zero for no nulls.
  2. Step 2: Analyze each option

    df.filter(df.age.isNull()).count() == 0 correctly checks if count of null age is zero. df.filter(df.age.isNotNull()).count() == 0 checks for non-null count equals zero, which is wrong. Options C and D use null with == or != which is invalid in Spark.
  3. Final Answer:

    df.filter(df.age.isNull()).count() == 0 -> Option A
  4. Quick Check:

    Use isNull() to find nulls, count should be zero [OK]
Hint: Use isNull() to find nulls, count zero means no nulls [OK]
Common Mistakes:
  • Using == null instead of isNull()
  • Checking isNotNull() count equals zero
  • Confusing null checks with non-null checks
3. Given the following Spark code, what will be the output?
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)
medium
A. 0
B. 1
C. 2
D. 3

Solution

  1. Step 1: Identify null values in the data

    The data has one row where age is None (null): the second row with Bob.
  2. Step 2: Count rows with null age

    The filter df.age.isNull() selects rows with null age, so count will be 1.
  3. Final Answer:

    1 -> Option B
  4. Quick Check:

    One null age value = 1 [OK]
Hint: Count rows with isNull() to find null entries [OK]
Common Mistakes:
  • Counting non-null rows instead of null rows
  • Misreading None as a valid age
  • Assuming no nulls without checking
4. You wrote this assertion to check if all values in column salary are positive:
assert df.filter(df.salary <= 0).count() == 0
But it passes even when there are null values in the salary column. What is the likely cause?
medium
A. The column salary contains null values, which are skipped by the comparison
B. The filter condition uses <= which is invalid in Spark
C. The count() method is not supported on DataFrames
D. The assert statement syntax is incorrect in Python

Solution

  1. Step 1: Understand filter behavior with nulls

    In Spark, null <= 0 evaluates to null, which is falsy in filter(), so null rows are skipped and not counted, causing the assertion to pass incorrectly when nulls exist.
  2. Step 2: Eliminate other options

    A: <= is valid in Spark filters. C: count() is supported on DataFrames. D: assert syntax is correct. B identifies the null-skipping issue.
  3. Final Answer:

    The column salary contains null values, which are skipped by the comparison -> Option A
  4. Quick Check:

    Nulls skipped in comparison filters [OK]
Hint: Nulls yield null in comparisons and are skipped by filter [OK]
Common Mistakes:
  • Not realizing nulls are skipped in comparison filters
  • Thinking comparisons catch nulls as invalid
  • Blaming syntax instead of null handling
5. You want to assert that a DataFrame df has no duplicate user_id values. Which Spark code correctly performs this data quality assertion?
hard
A. assert df.dropDuplicates().count() == df.count()
B. assert df.select('user_id').count() == df.count()
C. assert df.filter(df.user_id.isNull()).count() == 0
D. assert df.groupBy('user_id').count().filter('count > 1').count() == 0

Solution

  1. Step 1: Understand duplicate detection logic

    Duplicates mean some user_id appear more than once. Grouping by user_id and counting, then filtering counts > 1 finds duplicates.
  2. Step 2: Analyze each option

    A: df.dropDuplicates().count() == df.count() checks for completely identical rows across all columns, missing duplicates in user_id with differing other columns. B: df.select('user_id').count() == df.count() always true. C: Checks only nulls. D: Correctly finds groups with count > 1.
  3. Final Answer:

    assert df.groupBy('user_id').count().filter('count > 1').count() == 0 -> Option D
  4. Quick Check:

    Group and filter counts > 1 to find duplicates [OK]
Hint: Group by column, filter count > 1 to detect duplicates [OK]
Common Mistakes:
  • Using dropDuplicates() without column subset
  • Using count() without distinct or groupBy
  • Confusing null checks with duplicate checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard