Sub topic 2
Schema Inference and Schema Location
Assume basic Python, Spark DataFrames, Structured Streaming, Delta tables, and cloud storage paths. Auto Loader uses schema inference to determine the columns and types in incoming files. It stores this evolving schema at cloudFiles.schemaLocation, a durable path separate from the stream checkpoint.
Schema inference and the schema location
A schema location lets Auto Loader remember the schema it has already discovered. It prevents every restart from treating the input as new and provides a record of schema changes. Use a separate schema location for each input stream.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders"))Auto Loader may sample existing files when it first infers a schema. Later files are compared with the stored schema. The schema location must be writable, persistent, and accessible after a cluster restart.
Keeping unexpected data in `_rescued_data`
Unexpected data includes a new column, a value that does not match the expected type, or a column whose name differs only by case. Configure a rescued data column to preserve these values instead of silently dropping them.
With rescue schema evolution, unexpected fields are stored in _rescued_data as a map-like column. This protects data while you investigate the source change.
Controlling types with schema hints
Inference can choose an unsuitable type when early files contain ambiguous values. Schema hints pin important columns to specific types:
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.schemaHints", "order_id BIGINT, order_ts TIMESTAMP")
.option("rescuedDataColumn", "_rescued_data")
.load("/Volumes/main/raw/landing/orders"))Choosing a schema evolution mode
Choose the mode according to how strictly the producer contract is managed:
| Mode | Behavior |
|---|---|
| `addNewColumns` | Adds newly detected columns to the inferred schema |
| `rescue` | Keeps unexpected fields in `_rescued_data` |
| `failOnNewColumns` | Stops when a new column appears |
| `none` | Does not evolve the schema automatically |
failOnNewColumns is useful when upstream changes require approval. rescue is safer when ingestion must continue without losing fields.
Exercise
Which mode should you choose when the stream must continue while preserving unrecognized fields?
Show answer
Choose rescue and configure the _rescued_data column.