Sub topic 7
Controlling types with schema hints
This chapter covers how to fix column types in an Auto Loader stream when inference alone gives you the wrong ones. It assumes you have read the chapters on schema inference and on _rescued_data. You should also be comfortable with Spark DDL type names such as BIGINT, TIMESTAMP, and DECIMAL(18,2).
Why inference needs help
Auto Loader infers the schema of JSON and CSV files from a sample of the data and stores it in the schema location. By default, it treats every column in those formats as a string. This is deliberate. A column that holds 42 in the first file may hold "n/a" in the thousandth, and strings never fail to parse.
Strings are a poor type for a bronze table, though. You can't sort timestamps correctly, sum amounts, or compare ids without casting. There are two ways to get real types:
- Set
cloudFiles.inferColumnTypestotrue. Auto Loader then infersBIGINT,DOUBLE,TIMESTAMP, and similar types from the sampled values. - Set
cloudFiles.schemaHintsto pin specific columns to types you choose.
The two options work together. Inference handles the columns you don't care about, and hints override it for the columns where a wrong guess is expensive.
| Setup | JSON or CSV column result | Parquet or Avro column result |
|---|---|---|
| Defaults | `STRING` for every column | Type stored in the file |
| `inferColumnTypes` set to `true` | Type guessed from sampled values | Type stored in the file |
| `schemaHints` set | Hinted columns get your type. The rest follow one of the rows above. | Hinted columns get your type. The rest keep the file's type. |
Writing a hint
The value of cloudFiles.schemaHints is one string. It uses the same syntax as the column list in a CREATE TABLE statement: comma-separated pairs of column name and type.
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, amount DECIMAL(18,2)"
)
.load("/Volumes/main/raw/landing/orders")
.withColumn("source_file", col("_metadata.file_path")))
df.printSchema()Calling printSchema() on the streaming DataFrame is a cheap way to check the result. It triggers schema inference, so on the first run it writes the schema to the schema location. It does not start the stream.
A few rules apply to the hint string:
- Hints can use any Spark SQL type. That includes
DECIMAL(p,s),DATE,ARRAY<...>,MAP<...>, andSTRUCT<...>. - A column name with spaces or special characters needs backticks, for example `
Order IDBIGINT`. - A hint on a struct or array column describes the whole column. Write out the full type, such as
items ARRAY<STRUCT<sku: STRING, qty: INT>>. - Hints apply only when you don't pass an explicit schema with
.schema(...). If you provide a full schema, Auto Loader skips inference and ignores the hints.
Which columns to hint
Hint the columns where a wrong type causes silent damage or a later failure. These are the usual cases:
- Identifiers. A numeric-looking id such as
00123can be inferred as a number and lose its leading zeros. Hint it asSTRING. In the other direction, hint a large numeric id asBIGINTso it isn't inferred asDOUBLEand rounded. - Money. Inference produces
DOUBLEfor values with decimals, and floating point drifts. UseDECIMAL(18,2)or whatever precision your data needs. - Timestamps. Hinting
TIMESTAMPstates your intent explicitly. This matters when files mix formats or when some files hold only dates. - Columns that are empty in the sample. If every sampled row has
nullfor a column, inference has nothing to go on. A hint fixes the type before real values arrive. - Columns that may appear later. Hints cover columns you expect to arrive in future files, as well as columns that already exist.
Leave the rest to inference. A long hint string becomes a second schema definition that you have to maintain.
How a hinted value is read
When a file is parsed, each value is converted to the column's type. If the conversion fails, the row is still ingested and the failure goes into _rescued_data. The failure is not an error and it is not dropped.
Suppose order_id is hinted as BIGINT, and one file contains this record:
{"order_id": "A-1007", "order_ts": "2026-12-01T09:30:00Z", "amount": "19.90"}A-1007 cannot become a BIGINT. The row arrives with order_id set to null, and _rescued_data holds the original value along with the file it came from. Find these rows with a query like this one:
(spark.table("main.bronze.orders")
.where("_rescued_data IS NOT NULL")
.select("order_id", "source_file", "_rescued_data")
.show(truncate=False))A steady trickle of rescued values means a hint is wrong or a producer is sending bad data. Either way, you see it, which you would not with a plain CAST that returns null and keeps nothing.
Hints and schema evolution
Hints and schema evolution act at different times. Evolution decides what happens when a file contains a column that is not in the stored schema. Hints decide the type of a column when Auto Loader first records it.
With the default mode, addNewColumns, a stream that meets an unknown column stops with an error. It records the new column in the schema location and picks it up when you restart. If you hinted that column in advance, it enters the schema with your type. If you didn't, it enters with the inferred type, which is STRING when inferColumnTypes is off.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.option("cloudFiles.inferColumnTypes", "true")
.option("cloudFiles.schemaEvolutionMode", "addNewColumns")
.option(
"cloudFiles.schemaHints",
"order_id BIGINT, order_ts TIMESTAMP, discount DECIMAL(5,2)"
)
.load("/Volumes/main/raw/landing/orders"))Here discount may not exist in any file yet. When a producer starts sending it, the column enters the schema as DECIMAL(5,2).
The stored schema is the source of truth after the first run. Treat hints as something you settle before the first production run. If you change the type of a column that is already recorded, the target Delta table may reject the new type, and the old schema file may still apply. Test a type change against a copy of the table with a fresh schema location. Do not edit the production schema location by hand.
Choosing the hint type for the Delta table
The bronze table is created from the stream's schema the first time toTable runs. After that, the table's types are fixed, and a stream whose schema no longer matches fails the write. This gives you a practical rule: choose hints with the table in mind, not just the files. If you may later need amount as DECIMAL(18,2), hint it that way on day one. Widening later takes a table rewrite or a new column.
Exercise
A JSON feed has a customer_code field with values like 00482. With inferColumnTypes set to true and no hints, the bronze table shows 482. What is the fix, and why does it work?
Show answer
Add a hint such as customer_code STRING to cloudFiles.schemaHints. Inference sampled values that look like integers and chose a numeric type, which drops the leading zeros. The hint overrides inference for that column, so the original text is kept. Apply it before the first run, because the stored schema in the schema location and the Delta table both keep the numeric type once they exist.
Exercise
You hint order_id BIGINT. A new file contains the record {"order_id": "A-1007"}. What is in the row after ingestion, and how do you find it?
Show answer
The row is ingested with order_id equal to null, because A-1007 cannot be converted to BIGINT. The original value is stored in _rescued_data. Find such rows with WHERE _rescued_data IS NOT NULL, and use the source_file column from _metadata.file_path to identify the file that sent the bad value.