Sub topic 7
Reading files and tables
This chapter covers how to load data into a DataFrame from files and from tables. It assumes you can attach a notebook to compute, you know that spark is already defined, and you know what a schema is (covered in the previous chapter). Examples use Python.
The reader API
Every read starts from spark.read, which returns a DataFrameReader. You set a format, add options, optionally set a schema, and call load with a path. The call returns a DataFrame. Nothing is processed in full yet, because reading is lazy in the same way transformations are. Spark may inspect file metadata or sample files at this point, but it does not scan all the data until an action runs.
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
)The path above is a Unity Catalog volume path. Volumes are the usual place for files in current workspaces. Replace the path with one you can read, or the cell will fail with a "path does not exist" or permission error.
The same reader supports shortcuts such as spark.read.csv(path), spark.read.json(path) and spark.read.parquet(path). They are equivalent to format(...).load(...). This chapter uses the long form because the options are easier to see.
Explicit schema versus inference
Spark can guess column types with option("inferSchema", True). For CSV and JSON this costs an extra pass over the data, because Spark must read the values before it can pick types. Inference can also guess wrongly. For example, a column of zip codes becomes an integer and loses leading zeros, and a column that is empty in the sampled rows becomes a string.
An explicit schema avoids both problems. It skips the extra pass and gives you the same types on every run. The schema can be a DDL string, as above, or a StructType.
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, DateType, DoubleType
order_schema = StructType([
StructField("order_id", IntegerType(), True),
StructField("customer", StringType(), True),
StructField("order_date", DateType(), True),
StructField("amount", DoubleType(), True),
])You pass it with .schema(order_schema). The DDL string is shorter. The StructType form is easier to build in code or share between notebooks.
Formats and their differences
Not all formats need the same care.
| Format | Schema in the file? | Notes |
|---|---|---|
| CSV | No | Needs `header`, and usually an explicit schema. Delimiter, quoting and date formats are options. |
| JSON | No | Spark infers by default. Multi-line JSON documents need `multiLine`. |
| Parquet | Yes | Column types come from the file. Columnar, so unused columns are not read. |
| Delta | Yes | Types and history come from the table. Default table format on Databricks. |
For Parquet and Delta you normally do not set a schema. The file or table carries it.
events = spark.read.format("json").option("multiLine", True).load("/Volumes/main/default/raw/events/")
parquet_df = spark.read.format("parquet").load("/Volumes/main/default/raw/orders_parquet/")Passing a directory reads every file in it as one DataFrame. This is the normal way to load a dataset that was written as many part files.
Handling malformed rows
When a CSV row does not match your schema, Spark's behavior depends on the mode option.
PERMISSIVE(default): bad fields become null, and the row is kept.DROPMALFORMED: rows that do not parse are dropped silently.FAILFAST: the read fails on the first bad row.
PERMISSIVE can hide problems. If a column unexpectedly has many nulls after a read, check whether values are failing to parse. A wrong dateFormat is a common cause. During development, FAILFAST surfaces such problems immediately.
strict = (
spark.read.format("csv")
.option("header", True)
.option("mode", "FAILFAST")
.option("dateFormat", "yyyy-MM-dd")
.schema("order_id INT, customer STRING, order_date DATE, amount DOUBLE")
.load("/Volumes/main/default/raw/orders.csv")
)Because reads are lazy, a FAILFAST error may appear only when you run an action such as count(), not on the line that defines the DataFrame.
Reading tables
Data that is already registered in Unity Catalog is read by name, using the three-level catalog.schema.table form.
summary = spark.read.table("main.default.customer_summary")
# equivalent
summary = spark.table("main.default.customer_summary")Reading a table gives you the schema stored in the catalog, so there is nothing to declare. You need SELECT permission on the table and USE permission on its catalog and schema. If you see a permission error, check all three levels.
You can also read a table with SQL, which returns a DataFrame:
df = spark.sql("SELECT * FROM main.default.customer_summary WHERE total_amount > 100")Seeing how the read went
After any read, check the result before you build on it.
raw.printSchema()
display(raw.limit(10))printSchema shows the types Spark applied. limit(10) keeps the preview cheap. For file sources, input_file_name() is not supported in Unity Catalog compute in some modes, so use the _metadata.file_path column instead when you need to know which file a row came from:
with_source = raw.select("*", "_metadata.file_path")How the read is planned
The diagram shows what happens between the reader call and the first action.
This is why filters and column selections written after a read can reduce the work. With Parquet and Delta, Spark can skip columns you never use and skip files whose statistics rule out your filter.
Common errors
- Path not found or access denied. The path is wrong, or you lack
READ VOLUMEor table privileges. Test withdbutils.fs.ls("/Volumes/main/default/raw/"). - All columns are strings, or the header is a data row. You forgot
option("header", True). - Many unexpected nulls. A type or date format does not match the data. Switch to
FAILFASTto find the failing value. - A JSON read returns a single
_corrupt_recordcolumn. The file is a multi-line document. AddmultiLine. - Slow first read of a big CSV. You are probably using
inferSchema. Declare the schema.
Exercise
A CSV read with inferSchema turns a zip column such as "02134" into the integer 2134, and the job also takes longer than expected. What one change fixes both problems, and why?
Show answer
Replace inferSchema with an explicit schema that declares zip STRING. The explicit schema keeps the leading zero because the value is read as text, and it removes the extra pass over the data that inference needs.
Exercise
You run spark.read.format("csv").option("mode", "FAILFAST").schema(s).load(path) and no error appears, but df.count() later fails with a parse error. Why did the error appear late?
Show answer
Reads are lazy. Defining the DataFrame only describes the source, and the files are parsed when an action such as count() runs, so the malformed row is found then.