Sub topic 5
Schema inference and the schema location
This chapter assumes you know Spark DataFrames, the basics of Structured Streaming (readStream and writeStream), and Delta tables. You should also have seen the cloudFiles source from the earlier chapters. Here you will learn how Auto Loader decides what columns a file set has, where it keeps that decision, and what goes wrong when the setup is incomplete.
Why a streaming source needs a schema
A batch spark.read.json(path) can scan the files, work out a schema, and use it for that one job. A stream cannot do this in the same way. It runs many times, or forever, and each run must agree with the previous run about the shape of the data. If one run decides order_id is an integer and the next decides it is a string, the Delta table downstream breaks.
Auto Loader solves this by inferring the schema once from a sample of the data, then saving the result to a folder you name. Later runs read the saved schema instead of inferring again. That folder is the schema location.
The cloudFiles.schemaLocation option
The schema location is a path where Auto Loader stores the inferred schema and its history. You set it with cloudFiles.schemaLocation.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders"))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))On the first run, Auto Loader samples files from the input path, infers a schema, and writes it under _schemas/orders/_schemas. On later runs it loads that stored schema and skips inference. If you do not provide a schema and omit cloudFiles.schemaLocation, the stream fails at start with an error asking for a schema or a schema location.
Some practical rules:
- Use one schema location per stream. Two streams sharing a location overwrite each other's schema history.
- Keep it separate from the checkpoint folder, and do not put it inside the input path. Files written there would be picked up as input.
- You can point it at the same folder as the checkpoint only when you accept the coupling. Many teams keep it as a sibling folder, as in the example above, so each can be reset on its own.
- Use a path that survives the cluster. Volumes or cloud storage paths work. Local disk paths do not.
- Treat it as state. Deleting it forces a new inference on the next run.
If you supply an explicit schema with .schema(...), you do not need a schema location, because there is nothing to infer or evolve. You also lose evolution, covered in a later chapter.
What gets inferred and from how much data
Auto Loader does not read every file to infer. It samples up to a limit of bytes or files, whichever is reached first. The defaults are 50 GB or 1000 files. You can lower them to speed up the first run, or raise them for data whose shape varies a lot:
| Option | Meaning | Default |
|---|---|---|
| `cloudFiles.schemaInference.sampleSize.numBytes` | Maximum bytes sampled | 50 GB |
| `cloudFiles.schemaInference.sampleSize.numFiles` | Maximum files sampled | 1000 |
A column that only appears in file 5,000 will not be seen if sampling stops at 1000 files. That is not a bug: such a column will be handled by the rescue and evolution mechanisms from the next chapters.
Text formats default to strings
For JSON, CSV, and XML, Auto Loader infers every column as a STRING by default. This surprises many people, since spark.read.json would infer BIGINT or DOUBLE.
The reason is stability. A column that holds 1, 2, 3 in the first files might contain "N/A" later. If the column was inferred as integer, the later file would fail or lose data. A string accepts everything.
To get real types, set cloudFiles.inferColumnTypes to true:
from pyspark.sql.functions import col
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.inferColumnTypes", "true")
.option("cloudFiles.schemaHints", "order_id BIGINT, order_ts TIMESTAMP")
.option("cloudFiles.schemaEvolutionMode", "addNewColumns")
.load("/Volumes/main/raw/landing/orders")
.withColumn("source_file", col("_metadata.file_path")))With this option on, the sampled data decides the types, so a column of whole numbers becomes BIGINT and a column of decimals becomes DOUBLE. The risk is the same one described above: types come from a sample, and the sample may not show later values. Schema hints, covered in a later chapter, let you pin the columns you care about.
Binary-schema formats behave differently. Parquet and Avro files carry their own schema, so Auto Loader reads it from the files and the types are exact. It still stores the result in the schema location.
The saved schema as a versioned history
Inside the schema location, Auto Loader creates a _schemas directory. Each file in it is a numbered version of the schema, such as 0, 1, 2. Version 0 comes from first inference. A new version is written when the schema changes, for example when evolution adds a column.
This history is what lets a restarted stream pick up exactly where its schema left off. The stream reads the latest version, merges it with any hints, and continues from the checkpoint.
The two stores have separate jobs:
| Store | Records | Lost or deleted means |
|---|---|---|
| Checkpoint | Which files were processed | Files are read again from the beginning |
| Schema location | The column names and types | The schema is inferred again from a new sample |
Reading the schema back
You can check what Auto Loader stored by reading the schema directly from the stream. In a notebook, print it before you start the write:
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.inferColumnTypes", "true")
.load("/Volumes/main/raw/landing/orders"))
df.printSchema()Auto Loader runs inference when the stream is defined and the location is empty, so printSchema() shows the result of that first inference. Along with your columns you will see _rescued_data, which holds values that did not fit the schema. The next chapter covers it.
Common errors
The stream fails with a missing schema message. You gave neither .schema(...) nor cloudFiles.schemaLocation. Add one.
Every numeric column is a string. inferColumnTypes is off. Turn it on, or use schema hints for the columns you need.
A stored schema no longer matches what you want. Changing options such as inferColumnTypes after the first run has no effect on columns already in the saved schema. To re-infer, you must delete the schema location. Because the checkpoint relates to the same data, plan the reset as a deliberate step. Deleting only the schema location is usually safe for the file tracking, but the table you write to may need its own schema change.
Two streams overwrite each other's schema. They share a schema location. Give each stream its own.
The first run is very slow. Sampling up to 50 GB across many files takes time. Lower sampleSize.numBytes or numFiles if the files are uniform.
An empty input folder. With no files, there is nothing to infer from. A stream on an empty directory waits and infers when the first file arrives. Under availableNow with no files, the run finishes without creating a schema.
Decision guide
| Situation | Choice |
|---|---|
| Parquet or Avro input | Provide a schema location. Types come from the files. |
| JSON or CSV, loose types are acceptable | Leave defaults. All columns are strings. |
| JSON or CSV, you need typed columns | Set `inferColumnTypes` to `true` and add hints for key columns. |
| The data contract is fixed and known | Pass an explicit `.schema(...)` and skip inference. |
| Fast first run on uniform files | Lower the sample size options. |
Exercise
A team runs an Auto Loader stream over JSON files with only cloudFiles.format and cloudFiles.schemaLocation set. Their amount column shows up as a string in the Delta table, though every value in the files is a number. Why does this happen, and what is the minimum change to get a numeric type?
Show answer
For JSON, CSV, and XML, Auto Loader infers all columns as strings by default, so that later files with unexpected values cannot break the stream. Setting cloudFiles.inferColumnTypes to true makes it infer types from the sampled data. Because the schema is already saved, the team must also remove the existing schema location (or hint the column with cloudFiles.schemaHints "amount DOUBLE") for the change to take effect. Deleting the location should be planned, since the new types must match the target table.
Exercise
Name two things that are stored in the checkpoint and the schema location respectively, and say what happens if you delete each one.
Show answer
The checkpoint records which files have been processed. Deleting it makes the stream treat all files as new and ingest them again. The schema location records the inferred column names and types as numbered versions. Deleting it makes Auto Loader infer the schema again from a fresh sample on the next run.