Sub topic 6
Declaring partition schemas and types
The previous chapters showed that partition values live in directory names such as year=2024/country=DE. A path is only text, though. PyArrow has to turn that text into typed columns before you can filter on year >= 2023 or add the columns to a table. This chapter covers how that conversion works and when to declare the types yourself.
This chapter assumes you can read a pa.schema and have seen ds.dataset(..., partitioning="hive").
Where partition types come from
A partition field has two properties: a name and a type. The way you ask for partitioning decides where PyArrow gets each one.
| How you pass it | Names come from | Types come from |
|---|---|---|
| `partitioning="hive"` | the `key=` parts of the paths | inferred from the values |
| `ds.partitioning(flavor="hive")` with no schema | the `key=` parts of the paths | inferred from the values |
| `ds.partitioning(schema, flavor="hive")` | your schema | your schema |
| `ds.partitioning(field_names=[...])` | your list | inferred from the values |
| `ds.partitioning(schema)` (directory flavor) | your schema, by position | your schema |
Inference scans the directory names and picks the narrowest type that fits every value it sees. Values that look like integers typically become int32. Anything else becomes string. Inference is convenient, but two things can go wrong:
- The type may not be the one you wrote. If you wrote
yearasint16orint64, you read it back asint32. - The type depends on the data present. If one directory is named
year=unknown, the whole field falls back tostring.
A declared schema removes both problems. It also makes a bad directory name fail loudly instead of silently changing the column type.
Declaring a schema for Hive partitioning
You describe the partition columns with an ordinary pa.schema and pass it to ds.partitioning with flavor="hive":
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"year": pa.array([2023, 2023, 2024, 2024], pa.int16()),
"country": ["DE", "FR", "DE", "FR"],
"amount": [10.5, 20.0, 7.25, 3.0],
})
part = ds.partitioning(
pa.schema([("year", pa.int16()), ("country", pa.string())]),
flavor="hive",
)
ds.write_dataset(
table,
"sales_typed",
format="parquet",
partitioning=part,
existing_data_behavior="overwrite_or_ignore",
)
inferred = ds.dataset("sales_typed", format="parquet", partitioning="hive")
declared = ds.dataset("sales_typed", format="parquet", partitioning=part)
print("inferred:", inferred.schema.field("year").type)
print("declared:", declared.schema.field("year").type)Both opens read the same files. The first reports int32 for year and the second reports int16. The data on disk is identical, because the type exists only in the reader's interpretation of the path.
Pass the same partitioning object to the writer and the reader. That keeps the round trip consistent.
Directory partitioning needs a schema or names
Hive paths carry the column name, so PyArrow can discover it. Directory paths such as 2023/DE/ contain only values, so PyArrow must be told what each level means. Levels are matched by position, and the order of the fields is part of the layout:
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"year": pa.array([2023, 2024], pa.int16()),
"country": ["DE", "FR"],
"amount": [1.0, 2.0],
})
layout = ds.partitioning(
pa.schema([("year", pa.int16()), ("country", pa.string())])
)
ds.write_dataset(table, "sales_dir2", format="parquet", partitioning=layout)
# Paths: sales_dir2/2023/DE/part-0.parquet
by_names = ds.dataset(
"sales_dir2",
format="parquet",
partitioning=ds.partitioning(field_names=["year", "country"]),
)
print(by_names.schema)With field_names you supply names and PyArrow infers the types. If you swap the order to ["country", "year"], nothing raises an error at open time. The first level (2023) is read as country. Directory partitioning gives you no name to check against, so the schema order has to match the writer.
Dictionary-typed partition fields
A partition column such as country repeats the same few strings across many files. Declaring it as a dictionary type stores each distinct value once and uses small integer indices for the rows. PyArrow needs the full list of possible values up front:
import pyarrow as pa
import pyarrow.dataset as ds
schema = pa.schema([
("year", pa.int16()),
("country", pa.dictionary(pa.int32(), pa.string())),
])
part = ds.partitioning(
schema,
flavor="hive",
dictionaries={"country": pa.array(["DE", "FR", "US"])},
)
dataset = ds.dataset("sales_typed", format="parquet", partitioning=part)
print(dataset.schema.field("country").type)This is useful when the result goes to pandas as a categorical column, or when you group on the partition column. If a directory contains a value that is missing from the list (for example country=IT), the read fails. Dictionary partition fields suit values you control. Open-ended values are better left as plain strings.
What the partition schema does to the dataset schema
The dataset's schema is the file schema plus the partition fields, which are appended after the file columns. write_dataset does not write partition columns into the Parquet files. They exist only in the paths. This has consequences:
- Reading a single file with
pq.read_tableon a path likesales_typed/year=2024/country=DE/part-0.parquetreturns noyearorcountrycolumn. - A partition field name that is also a physical column in the files is a conflict. Do not duplicate it. If you need the value both in the path and in the file, keep a copy under a different name before writing.
- Each fragment holds the parsed values as
fragment.partition_expression. For a file underyear=2024/country=DEit is(year == 2024) and (country == "DE"), using the declared types.
Type choices that matter for filters
Filters compare partition expressions with your literals, so the declared type affects which filters work. Suppose year was inferred or declared as string. Then ds.field("year") == 2024 compares a string to an integer and fails or matches nothing, depending on your version. You would write ds.field("year") == "2024" instead. Declaring numeric partition columns as integers also gives correct ordering. As strings, "10" sorts before "9", so a range filter like >= 9 would give wrong answers.
Some practical rules:
- Use integers for years, months and numeric IDs, and pick the width yourself (
int16for years is enough). - Use
stringfor codes that can have leading zeros, such as"007". An integer type would turn them into7. - Use
pa.date32()only when the directory names are ISO dates like2024-03-01. Test it on your PyArrow version first. - Keep the partition schema in one shared module so the writer and every reader agree.
Common errors
- A value cannot be parsed to the declared type. A directory like
year=n/aunder an integer schema raises anArrowInvaliderror when the path is parsed. Either fix the directory or declare the field asstring. - A type changes after new data arrives. An inferred field can flip from
int32tostringwhen one odd directory appears. Declare the schema to prevent this. - Directory columns are mislabeled. This comes from a wrong field order, as shown above. Print
fragment.partition_expressionfor a few fragments and check the values against the paths.
Exercise
A dataset is stored as 2024/03/part-0.parquet, where the first level is the year and the second is the month. You open it with ds.partitioning(field_names=["month", "year"]). What happens, and how do you make the types explicit and correct?
Show answer
Nothing fails at open time. Directory partitioning matches levels by position, so 2024 is read as month and 03 as year, and filters return wrong or empty results. The fix is to use the right order and declare the types: ds.partitioning(pa.schema([("year", pa.int16()), ("month", pa.int8())])). If you need the month to keep its leading zero, declare it as pa.string().