Schema evolution and enforcement help keep data organized and consistent when it changes over time.
Schema evolution and enforcement in Apache Spark
spark.read.option("mergeSchema", "true").parquet("path/to/data") // To enforce schema import org.apache.spark.sql.types._ val schema = new StructType().add("name", StringType).add("age", IntegerType) spark.read.schema(schema).json("path/to/json")
Use mergeSchema=true to allow Spark to combine different schema versions.
Use .schema() to enforce a fixed schema when reading data.
val df = spark.read.option("mergeSchema", "true").parquet("/data/events") df.printSchema()
import org.apache.spark.sql.types._ val fixedSchema = new StructType() .add("id", IntegerType) .add("name", StringType) .add("score", DoubleType) val df = spark.read.schema(fixedSchema).json("/data/scores.json") df.printSchema()
This example shows how to save data with one schema, add new data with an extra column, and then read both together by merging schemas.
import org.apache.spark.sql.SparkSession import org.apache.spark.sql.types._ val spark = SparkSession.builder.appName("SchemaEvolutionExample").master("local").getOrCreate() // Create first DataFrame with schema v1 val dataV1 = Seq((1, "Alice"), (2, "Bob")) val schemaV1 = new StructType().add("id", IntegerType).add("name", StringType) val dfV1 = spark.createDataFrame(spark.sparkContext.parallelize(dataV1), schemaV1) // Save as parquet val path = "./temp_parquet" dfV1.write.mode("overwrite").parquet(path) // Create second DataFrame with schema v2 (new column 'age') val dataV2 = Seq((3, "Charlie", 30), (4, "David", 40)) val schemaV2 = new StructType().add("id", IntegerType).add("name", StringType).add("age", IntegerType) val dfV2 = spark.createDataFrame(spark.sparkContext.parallelize(dataV2), schemaV2) // Append new data with new schema dfV2.write.mode("append").parquet(path) // Read with mergeSchema option to combine both schemas val mergedDF = spark.read.option("mergeSchema", "true").parquet(path) mergedDF.printSchema() mergedDF.show() spark.stop()
Schema evolution works well with file formats like Parquet and Delta Lake.
Enforcing schema helps catch errors early if data does not match expected types.
Always test schema changes on a small dataset before applying to big data.
Schema evolution lets you add or change columns without breaking old data.
Schema enforcement ensures data matches the expected format.
Use mergeSchema option to combine different schema versions when reading.
Practice
Solution
Step 1: Understand schema evolution concept
Schema evolution means you can update the schema by adding or changing columns without losing compatibility with existing data.Step 2: Compare options with definition
Only Add or change columns without breaking old data correctly describes this ability. Other options describe unrelated features.Final Answer:
Add or change columns without breaking old data -> Option AQuick Check:
Schema evolution = Add/change columns safely [OK]
- Confusing schema evolution with schema enforcement
- Thinking schema evolution deletes old data
- Assuming schema evolution compresses data
Solution
Step 1: Recall correct option name for schema merging
The correct option to merge schemas is "mergeSchema" set to "true".Step 2: Verify syntax correctness
spark.read.option("mergeSchema", "true").parquet(path) uses the exact syntax spark.read.option("mergeSchema", "true").parquet(path), which is valid.Final Answer:
spark.read.option("mergeSchema", "true").parquet(path) -> Option DQuick Check:
Use mergeSchema=true to merge schemas [OK]
- Using wrong option names like enforceSchema or schemaEvolution
- Setting mergeSchema to false disables merging
- Confusing option names with other Spark settings
file1: (id INT, name STRING)file2: (id INT, name STRING, age INT)What will be the schema of the DataFrame when reading both files with
mergeSchema=true?Solution
Step 1: Understand schema merging behavior
When mergeSchema=true, Spark combines all columns from all files, including new columns.Step 2: Combine columns from both schemas
file1 has (id, name), file2 adds (age). Merged schema includes all three columns.Final Answer:
(id INT, name STRING, age INT) -> Option AQuick Check:
Merged schema includes all columns from files [OK]
- Ignoring new columns in second file
- Assuming schema stays as first file only
- Dropping columns not in all files
Solution
Step 1: Identify cause of schema mismatch error
Schema mismatch errors happen when Spark tries to read files with different schemas without merging enabled.Step 2: Check mergeSchema option usage
Not setting mergeSchema=true causes Spark to expect identical schemas, leading to errors.Final Answer:
You did not set mergeSchema option to true -> Option BQuick Check:
Enable mergeSchema=true to avoid schema mismatch errors [OK]
- Blaming file corruption without checking options
- Assuming Spark cannot evolve schemas
- Ignoring mergeSchema option
age INT and keep old data accessible. Which approach correctly applies schema evolution and enforcement?Solution
Step 1: Add new column using ALTER TABLE
ALTER TABLE ADD COLUMN adds the new column to the Delta table schema safely.Step 2: Write new data with mergeSchema=true
Writing with mergeSchema=true allows Spark to merge new schema with old data without errors.Final Answer:
Use ALTER TABLE ADD COLUMN age INT and write new data with mergeSchema=true -> Option CQuick Check:
ALTER TABLE + mergeSchema=true enables safe schema evolution [OK]
- Overwriting schema without mergeSchema causes data loss
- Deleting old data loses history
- Appending without mergeSchema causes errors
Ready to prove it?
Pass the test and this pattern moves unknown
