Sub topic 6
Schemas and data types
This chapter assumes you can attach a notebook to compute in Databricks and that you know basic Python or SQL. It also assumes you have already built a small DataFrame with spark.createDataFrame. Here you will learn what a schema is, which types you will meet most often, and how to set a schema yourself instead of letting Spark guess.
What a schema is
A schema is the list of column names, column types, and nullability flags for a DataFrame. Spark knows the schema before it runs any job, so it can check your column names and types when you write a transformation. A wrong column name fails right away with an analysis error. It does not fail halfway through a long job.
You can inspect the schema with printSchema():
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.printSchema()
display(orders)The schema here is a DDL-style string: comma-separated name TYPE pairs. printSchema() shows order_date as date after the conversion. Before the withColumn call it was string.
Common data types
| Type | Holds | Example |
|---|---|---|
| `INT`, `BIGINT` | Whole numbers (32-bit, 64-bit) | `order_id` |
| `DOUBLE` | Floating-point numbers | `amount` |
| `DECIMAL(p, s)` | Exact decimals | currency |
| `STRING` | Text | `customer` |
| `DATE`, `TIMESTAMP` | Calendar dates and points in time | `order_date` |
| `BOOLEAN` | True or false | flags |
| `ARRAY`, `STRUCT`, `MAP` | Nested values | lists, records |
Use DECIMAL for money when exact cents matter. DOUBLE is binary floating point and can introduce small rounding errors.
Setting the schema when you read
When Spark reads a CSV file, every column is a string unless you tell it otherwise. You can ask Spark to infer types with inferSchema, but that costs an extra pass over the data, and the guessed types can change when the data changes. An explicit schema avoids both problems:
raw = (
spark.read
.format("csv")
.option("header", True)
.schema("order_id INT, customer STRING, order_date DATE, amount DOUBLE")
.load("/Volumes/main/default/raw/orders.csv") # replace with a path you can read
)Common errors
- Dates stay as strings. A column typed
STRINGsorts and compares as text. Convert it withF.to_dateor declareDATEin the schema. - Numbers read as strings. If any value in a column is not numeric and you are inferring types, the whole column becomes
string. An explicit schema surfaces the bad values as nulls. - Casting silently produces nulls.
F.col("x").cast("int")returnsnullfor text that is not a number (unless ANSI mode is on). Count nulls before and after a cast to see what was lost.
Exercise
You read a CSV with inferSchema and the amount column comes back as string, although most values look like numbers. What is the likely cause, and how would you fix it?
Show answer
At least one value is not a valid number, such as "N/A" or a stray symbol, so Spark infers the whole column as string. Fix it by supplying an explicit schema with amount DOUBLE. Unparseable values then become null, and you can find and handle them.