Sub topic 2
Reading files with the cloudFiles source
This chapter assumes you can read PySpark code and have used readStream and writeStream before. You should know what a Delta table is and how cloud storage paths such as /Volumes/... or s3://... look. Checkpoints, triggers, and schema handling each get their own chapter, so this chapter only shows where they plug in.
What the cloudFiles source is
Auto Loader is not a separate API. It is a Structured Streaming source named cloudFiles. You select it with format("cloudFiles") on spark.readStream. The result is an ordinary streaming DataFrame, so every transformation, join, and sink you already know works on it.
The source's job is narrow. It finds files in a storage path that it has not seen before, reads them in the format you name, and hands the rows to the stream. It remembers which files it has already handled, so you do not list directories or track filenames yourself.
The following diagram shows where the source sits in a typical pipeline.
A minimal stream
This is the smallest useful Auto Loader pipeline. It reads new JSON files from a landing folder and appends them to a Delta table.
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"))Each part does a specific job:
format("cloudFiles")selects the Auto Loader source instead of the plain file source.cloudFiles.formatnames the format of the files being read, not the source itself.cloudFiles.schemaLocationis a directory where Auto Loader stores the schema it infers. Without it, inference has nowhere to persist its result.load(...)takes the input path to watch.checkpointLocationon the writer stores progress, so a restart continues where the last run stopped.trigger(availableNow=True)processes everything pending and then stops.toTable(...)appends to a Delta table in Unity Catalog.
Keep the schema location and the checkpoint in separate directories. Both belong to one stream, so give each stream its own pair. Sharing them between streams corrupts state.
Choosing the file format
The cloudFiles.format option accepts these values:
| Value | File type |
|---|---|
| `json` | JSON, one record per line by default |
| `csv` | Delimited text |
| `parquet` | Parquet |
| `avro` | Avro |
| `orc` | ORC |
| `text` | Plain text, one row per line |
| `binaryFile` | Whole files as binary content |
| `xml` | XML |
One stream reads one format. If a folder mixes JSON and CSV files, filter the files with a path glob or use separate streams.
Options: Auto Loader versus the format reader
The source accepts two kinds of options, and mixing them up is a common mistake.
- Options that start with
cloudFiles.configure Auto Loader itself. Examples arecloudFiles.format,cloudFiles.schemaLocation, andcloudFiles.useNotifications. - All other options go to the underlying format reader. For CSV, that means
header,delimiter, andquote. For JSON, it means options such asmultiLine.
The CSV example below shows both kinds together.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("header", "true")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/events")
.option("cloudFiles.useNotifications", "true")
.option("cloudFiles.maxFilesPerTrigger", "500")
.load("s3://my-bucket/landing/events"))Here header is a CSV reader option. The three cloudFiles.* options set the format, the schema location, the discovery mode, and the batch size. The discovery mode and batch size are covered in later chapters. For now, treat them as settings you can add to the same chain.
If you forget header, the first line of each CSV file is read as data, and the columns get generic names. Auto Loader does not warn you, because from its point of view the file was read correctly.
Supplying a schema yourself
Inference is convenient, but you can skip it. If you call .schema(...) on the reader, Auto Loader uses your schema and does not need a schema location.
from pyspark.sql.types import StructType, StructField, LongType, StringType, TimestampType
orders_schema = StructType([
StructField("order_id", LongType()),
StructField("customer", StringType()),
StructField("order_ts", TimestampType()),
])
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.schema(orders_schema)
.load("/Volumes/main/raw/landing/orders"))An explicit schema gives you stable types, but it also means that new fields in the source files are ignored unless you handle them another way. The next chapters cover how inference, hints, and evolution give you more flexibility.
Which files the source picks up
The input path is the root of the search. Auto Loader reads files in that directory and in its subdirectories. A path can include glob patterns, so you can target a layout such as one folder per day.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "parquet")
.schema("order_id BIGINT, amount DOUBLE")
.load("/Volumes/main/raw/landing/orders/2026-*/"))Some rules matter in practice:
- Files are expected to be complete when they appear. Write files to a temporary location and move them into the landing folder, or use a naming scheme the glob excludes. A file that is still being written can be read half-finished.
- By default, a file is processed once. If someone overwrites a file in place after it was ingested, Auto Loader does not read it again. An option exists to change this (
cloudFiles.allowOverwrites), but it can produce duplicate rows, so treat it as a deliberate choice and not a fix. - Files that existed before the stream's first run are picked up on that first run, unless you configure otherwise. Later chapters cover this backfill behavior.
- Hidden files and folders, whose names begin with an underscore or a dot, are ignored. This is why folders such as
_schemasand_checkpointsare safe to keep beside the data, though a separate location is cleaner.
What the DataFrame contains
When Auto Loader infers the schema, the DataFrame holds the columns found in the data. It also adds a column named _rescued_data, which captures values that do not fit the schema. That column is the subject of its own chapter.
You can also reach file-level information through the hidden _metadata column. It is not included in select *, so you request it by name.
from pyspark.sql.functions import col
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders")
.withColumn("source_file", col("_metadata.file_path")))This keeps each row traceable to the file that produced it. Doing it at ingestion time is much cheaper than trying to reconstruct it later.
Common errors
These problems show up often when people first use the source:
- A missing schema location. If you rely on inference and omit
cloudFiles.schemaLocation, the stream fails at start. Add the option, or provide a schema. - Reusing paths between streams. Two streams writing to one checkpoint or schema location overwrite each other's state. Use one directory per stream.
- A wrong
cloudFiles.format. If the files are CSV but you sayjson, the data lands mostly in_rescued_dataor comes out as nulls. Check the format first when the output looks empty. - Confusing the source with the plain file source.
format("json")onreadStreamalso works, but it re-lists the directory and offers none of the discovery, schema, or rescue features. UsecloudFilesfor ingestion. - Forgetting the writer side. The read does nothing until a
writeStreamstarts. Errors about a missing checkpoint come from the writer, not the source.
Check your understanding
Exercise
A stream reads CSV files with the cloudFiles source. The output table has columns named c0, c1, and _c2, and the first data row contains the header text. Which option is missing, and is it a cloudFiles option or a format reader option?
Show answer
The header option is missing. It is a format reader option for CSV, so you write .option("header", "true") without the cloudFiles. prefix. Only options such as cloudFiles.format and cloudFiles.schemaLocation configure Auto Loader itself.
Exercise
You start an Auto Loader stream with cloudFiles.format set to json and no schema, but you leave out cloudFiles.schemaLocation. What happens, and what are two ways to fix it?
Show answer
The stream fails at start because inference has nowhere to store the inferred schema. Fix it by adding cloudFiles.schemaLocation pointing to a directory used only by this stream, or by supplying a schema with .schema(...) so no inference is needed.