Sub topic 9
Tracking the source file with _metadata
This chapter assumes you can already write a basic Auto Loader stream with cloudFiles, and that you know what a Delta table is. You should be comfortable selecting columns and adding columns in PySpark or SQL. It covers how to record which file each row came from, and what to watch for when you do.
Why record the source file
A bronze table that holds only the data from the files is hard to debug. When a downstream report shows a strange value, you need to answer three questions:
- Which file did this row come from?
- When was that file last modified?
- Did other rows come from the same file?
Recording the source file gives you lineage, which is the trail from a row back to the file that produced it. It also supports audits, targeted reprocessing, and cleanup after a bad delivery. You can store the file path as an ordinary column, so these questions become plain queries.
The _metadata column
Spark file sources expose a hidden column named _metadata. It is a struct, which means a single column that contains named fields. Auto Loader reads files through the same file source machinery, so the column is available in your cloudFiles stream.
| Field | Type | Meaning |
|---|---|---|
| `file_path` | STRING | Full path of the file, including the storage scheme |
| `file_name` | STRING | The file name without its directory |
| `file_size` | BIGINT | Size of the file in bytes |
| `file_modification_time` | TIMESTAMP | Last modification time of the file |
| `file_block_start` | BIGINT | Start offset of the block being read |
| `file_block_length` | BIGINT | Length in bytes of the block being read |
In practice you will use the first four. The two block fields describe how Spark split a large file into chunks for reading. They are rarely useful for ingestion.
The column is hidden, so a plain select * does not return it. You must name it. That is the most common mistake: people read the data, write it to a table, and later find that no file information exists anywhere.
Adding file information to the stream
Select the fields you want as normal columns before writing. Aliasing them gives readable names in the target table.
from pyspark.sql.functions import col, current_timestamp
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders")
.select(
"*",
col("_metadata.file_path").alias("source_file"),
col("_metadata.file_name").alias("source_file_name"),
col("_metadata.file_size").alias("source_file_size"),
col("_metadata.file_modification_time").alias("source_file_modified"),
current_timestamp().alias("ingested_at"),
))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))The current_timestamp() column is not part of _metadata. It records when your job processed the row, which is different from when the file was modified. Keeping both lets you measure ingestion delay: ingested_at minus source_file_modified.
You can also keep the whole struct in one column:
df_with_struct = df_raw.withColumn("_file", col("_metadata"))Here df_raw stands for any DataFrame returned by load(). Storing the struct keeps every field, at the cost of a nested column that is a little harder to filter and join on. For most teams, a few flat columns are easier to use.
The same thing in SQL
In a streaming table definition, reference _metadata in the SELECT list.
CREATE OR REFRESH STREAMING TABLE orders_bronze AS
SELECT
*,
_metadata.file_path AS source_file,
_metadata.file_modification_time AS source_file_modified
FROM STREAM read_files(
'/Volumes/main/raw/landing/orders',
format => 'json'
);The rule is the same as in Python. * does not include _metadata, so you add the fields you need.
Using the path in queries
Once the path is a normal column, you can use it like any other.
To see how many rows each file delivered:
SELECT source_file, COUNT(*) AS row_count
FROM main.bronze.orders
GROUP BY source_file
ORDER BY row_count DESC;To remove everything that came from one bad file:
DELETE FROM main.bronze.orders
WHERE source_file = 'dbfs:/Volumes/main/raw/landing/orders/2026-12-01/orders_001.json';The exact string in file_path includes a scheme prefix, such as dbfs:/ or s3://, depending on where the file lives. Run a SELECT DISTINCT source_file ... LIMIT 5 first and copy the format you see, instead of assuming it. A filter that does not match the stored format deletes nothing and gives no error.
Deriving values from the path
Many landing zones put information in the folder structure, such as a date or a source system name. The file path lets you turn that into a column without changing the files.
from pyspark.sql.functions import col, regexp_extract
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"))
.withColumn(
"delivery_date",
regexp_extract(col("source_file"), r"/(\d{4}-\d{2}-\d{2})/", 1).cast("date"),
))For a file at /Volumes/main/raw/landing/orders/2026-12-01/orders_001.json, delivery_date is 2026-12-01. If the pattern does not match, regexp_extract returns an empty string, and the cast turns that into null. Check for nulls in delivery_date after the first run, because a new folder layout will silently produce them.
Edge cases and gotchas
- A data column named
_metadata. If your files contain a field called_metadata, the data column takes precedence over the file metadata. Your queries then return the data field, and you cannot reach the file fields by that name. Check your source schema for this name before you rely on the column. - Replaced files. If a producer overwrites a file at the same path, the path stays the same, but
file_modification_timechanges. Auto Loader only picks up overwritten files when you setcloudFiles.allowOverwrites. When you do, a path can appear in the table more than once, from different versions of the file. Keep the modification time alongside the path so you can tell versions apart. - Row count per file is not a file count. Grouping by
source_filecounts rows. A file that produced zero rows, for example an empty file, never appears in your table. - Storage cost. A full path string repeated on every row compresses well in Delta, because many rows share the same value. The cost is usually small, but a very wide struct of many fields adds up on billions of rows.
- Old approach. Earlier code used the
input_file_name()function for the same purpose. It is deprecated in newer runtimes, and_metadatais the supported replacement. Prefer_metadatain new work. - Schema evolution is unaffected. Because
_metadatais outside the inferred schema, adding it never triggers a schema change, and yourschemaEvolutionModesetting has no effect on it. A column you derive from it, likesource_file, is a normal column in the target table.
Putting it together with the earlier options
Metadata columns combine with the options from earlier chapters. This example uses schema hints and an explicit evolution mode, and it adds the path:
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")))The source_file column is added after the load, so it never enters the schema stored at the schema location. When the stream restarts after a schema change, the column is still added in the same way.
Summary
_metadatais a hidden struct with file path, name, size, and modification time.- Select it explicitly, because
select *leaves it out. - Copy the fields into normal columns before you write, because the information is not stored anywhere else.
- Check the stored path format before you filter on it.
- Watch for a data column with the same name, and for overwritten files that reuse a path.
Exercise
A teammate's bronze table was created with .load(...) followed directly by .writeStream.toTable(...). A week later they want to know which file each row came from, so they add col("_metadata.file_path") to the stream and restart it with the same checkpoint. Will the old rows get a source_file value? What would you do to get one for all rows?
Show answer
No. The checkpoint records that the old files were already processed, so the stream will not read them again, and the old rows have no file path (the new column is null for them, or the write fails if the table schema does not allow the new column). To get the path for all rows, run a new stream with a new checkpoint and schema location, with the metadata column selected, against the same landing folder, and write to a new table. This re-reads every file. Use the new table going forward, then retire the old one.
Exercise
You run DELETE FROM main.bronze.orders WHERE source_file = '/Volumes/main/raw/landing/orders/2026-12-01/orders_001.json'. It succeeds but deletes zero rows, although you know rows from that file exist. What is the most likely cause, and how do you check it?
Show answer
The stored file_path value includes a scheme prefix such as dbfs:/ that your literal does not have, so the comparison never matches. Run SELECT DISTINCT source_file FROM main.bronze.orders LIMIT 5, copy the exact format, and filter with it. A LIKE '%orders_001.json' filter is a way to confirm the file is present.