📖 Scenario: You work in a company that collects customer data. You want to make sure the data is clean and follows the correct format before analysis.
🎯 Goal: You will create a Spark DataFrame with customer data, define a schema to validate the data types, and check if the data matches the schema.
📋 What You'll Learn
Create a Spark DataFrame with given customer data
Define a schema with correct data types for each column
Apply the schema to the DataFrame to validate data
Show the validated DataFrame
💡 Why This Matters
🌍 Real World
Data scientists often receive raw data that may have inconsistent types. Schema validation helps ensure data quality before analysis.
💼 Career
Knowing how to define and apply schemas in Spark is essential for data engineers and data scientists working with big data pipelines.
Progress0 / 4 steps
1
Create customer data as a list of tuples
Create a variable called customer_data as a list of tuples with these exact entries: (1, 'Alice', 29), (2, 'Bob', 35), (3, 'Charlie', 40).
Apache Spark
Hint
Use square brackets to create a list and parentheses for each tuple.
2
Define the schema for the customer data
Create a variable called schema using StructType with three fields: id as IntegerType(), name as StringType(), and age as IntegerType(). Import the necessary types from pyspark.sql.types.
Apache Spark
Hint
Use StructType and StructField to define the schema fields.
3
Create a Spark DataFrame with the schema
Create a Spark DataFrame called df from customer_data using spark.createDataFrame() and apply the schema to it.
Apache Spark
Hint
Use spark.createDataFrame() with the schema argument.
4
Show the validated DataFrame
Use printSchema() on df to display the schema, then use df.show() to display the data.
Apache Spark
Hint
Use df.printSchema() to see the schema and df.show() to see the data.
Practice
(1/5)
1. What is the main purpose of schema validation in Apache Spark?
easy
A. To check if the data matches the expected format before processing
B. To speed up the Spark job execution
C. To automatically clean the data
D. To visualize data distributions
Solution
Step 1: Understand schema validation role
Schema validation ensures data matches the expected structure and types before analysis.
Step 2: Identify the main goal
This helps catch errors early and prevents processing wrong data formats.
Final Answer:
To check if the data matches the expected format before processing -> Option A
Quick Check:
Schema validation = format check [OK]
Hint: Schema validation means checking data format first [OK]
Common Mistakes:
Thinking schema speeds up execution directly
Assuming schema cleans data automatically
Confusing schema validation with visualization
2. Which of the following is the correct way to define a schema with two fields: 'name' as string and 'age' as integer in Spark?
easy
A. Schema(['name': 'string', 'age': 'int'])
B. StructType('name' StringType, 'age' IntegerType)
C. StructType([StructField('name', StringType()), StructField('age', IntegerType())])
D. StructField('name', 'string'), StructField('age', 'int')
Solution
Step 1: Recall correct schema syntax
In Spark, schema is defined using StructType with a list of StructField objects specifying name and type.
Step 2: Match syntax to options
StructType([StructField('name', StringType()), StructField('age', IntegerType())]) correctly uses StructType with StructField and proper types.
Final Answer:
StructType([StructField('name', StringType()), StructField('age', IntegerType())]) -> Option C
Quick Check:
Schema = StructType + StructField [OK]
Hint: Use StructType with list of StructField for schema [OK]
But you get an error: TypeError: StructField() missing 1 required positional argument: 'nullable'. What is the fix?
medium
A. Add the 'nullable' argument to each StructField, e.g. StructField('id', IntegerType(), True)
B. Remove the schema and let Spark infer it
C. Change StructType to SchemaType
D. Use a list of tuples instead of StructField
Solution
Step 1: Understand StructField parameters
StructField requires three arguments: name, data type, and nullable (True/False).
Step 2: Fix the code by adding nullable
Add the third argument 'nullable=True' to each StructField to fix the error.
Final Answer:
Add the 'nullable' argument to each StructField, e.g. StructField('id', IntegerType(), True) -> Option A
Quick Check:
StructField needs nullable argument [OK]
Hint: Always include nullable in StructField [OK]
Common Mistakes:
Forgetting nullable argument
Trying to rename StructType
Ignoring error and running code
5. You have a CSV file with columns: 'user', 'score', and 'date'. You want to read it with Spark and ensure 'score' is an integer and 'date' is a date type. Which schema definition and read method is correct to validate this?