Sub topic 9
Building filter expressions with ds.field
This chapter assumes you can write basic Python and have read the earlier chapters on datasets, fragments and partition schemas. You should know that a dataset exposes partition values such as year and country as ordinary columns. Here you learn to write the conditions that select rows from those columns.
What an expression is
ds.field("year") does not read any data. It returns an Expression object, which is a description of a computation. Comparing it to a value produces another expression.
import pyarrow.dataset as ds
expr = ds.field("year") == 2024
print(type(expr))
print(expr)The first line prints <class 'pyarrow._compute.Expression'>. The second prints the expression in text form, (year == 2024). Nothing has been evaluated, because no table exists yet. You pass the expression to filter= on to_table, scanner or dataset.scanner. The dataset layer then decides how to apply it.
This laziness is the main reason to use expressions instead of filtering a Python table afterwards. The scanner can read the expression, compare it with partition values and Parquet statistics, and skip data before reading it. The next chapter covers that pruning in detail.
Comparison, membership and null tests
The operators on a field expression are the usual ones. Methods cover the cases that operators cannot express.
| Goal | Expression |
|---|---|
| Equal, not equal | `ds.field("a") == 1`, `ds.field("a") != 1` |
| Ordering | `<`, `<=`, `>`, `>=` |
| Value in a set | `ds.field("a").isin([1, 2, 3])` |
| Value is null | `ds.field("a").is_null()` |
| Value is not null | `ds.field("a").is_valid()` |
| Literal on the left | `ds.scalar(5) < ds.field("a")` |
Normally you do not need ds.scalar. Python converts plain values for you when the field is on one side of the operator. ds.scalar helps when you want an explicit literal, for example when the value's type matters.
Combining expressions
Combine expressions with & (and), | (or) and ~ (not). Python's and, or and not do not work. They ask Python for a true or false value, and an expression cannot provide one, so PyArrow raises an error. For the same reason, a chained comparison such as 2022 < ds.field("year") < 2025 fails, because Python expands it into an and.
Wrap each side in parentheses. In Python, & binds more tightly than ==, so ds.field("year") == 2024 & ds.field("country") == "DE" is parsed in a way you did not intend. Parentheses fix it.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"year": [2023, 2023, 2024, 2024],
"country": ["DE", "FR", "DE", "FR"],
"amount": [10.5, 20.0, 7.25, None],
})
dataset = ds.dataset(table)
def show(label, expr):
result = dataset.to_table(filter=expr)
print(label, result.num_rows, result.column("amount").to_pylist())
year = ds.field("year")
country = ds.field("country")
amount = ds.field("amount")
show("2024 and DE:", (year == 2024) & (country == "DE")) # 1 [7.25]
show("2023 or big: ", (year == 2023) | (amount > 5)) # 3 [10.5, 20.0, 7.25]
show("FR only: ", country.isin(["FR"])) # 2 [20.0, None]
show("null amount: ", amount.is_null()) # 1 [None]
show("not > 5: ", ~(amount > 5)) # 0 []Passing a Table to ds.dataset gives an in-memory dataset. Expressions behave the same way on it as on files, which makes it a quick place to test a filter.
Nulls and three-valued logic
The last line of the example returns zero rows. That surprises many people. For the row with a null amount, amount > 5 evaluates to null, not false. Negating null gives null again. A filter keeps only rows where the expression is true, so the null row is dropped both by amount > 5 and by ~(amount > 5).
The same rule explains the third result. For the row (2024, FR, None), the expression (year == 2023) | (amount > 5) is false | null, which is null, so the row is dropped.
Types must be compatible
A comparison needs both sides to have compatible types. Hive partitioning infers integer-looking directory names as integers, so ds.field("year") == 2024 works. If you declared year as a string in the partition schema, you must compare with "2024". If PyArrow cannot reconcile the types, it raises an error when the scan runs, not when you build the expression. This is the cost of laziness. A typo in a column name or a type mismatch surfaces only at scan time.
Building filters from data
Expressions are ordinary Python objects, so you can build them in loops. A common case is turning user-supplied options into one filter. functools.reduce with operator.and_ joins a list of expressions.
import operator
from functools import reduce
import pyarrow as pa
import pyarrow.dataset as ds
def build_filter(**conditions):
parts = []
for name, value in conditions.items():
field = ds.field(name)
if isinstance(value, (list, tuple, set)):
parts.append(field.isin(list(value)))
else:
parts.append(field == value)
return reduce(operator.and_, parts) if parts else None
table = pa.table({
"year": [2023, 2023, 2024, 2024],
"country": ["DE", "FR", "DE", "FR"],
"amount": [10.5, 20.0, 7.25, 3.0],
})
dataset = ds.dataset(table)
flt = build_filter(year=2024, country=["DE", "FR"])
print(flt)
print(dataset.to_table(filter=flt).num_rows) # 2
print(dataset.to_table(filter=build_filter()).num_rows) # 4, no filter at allPassing filter=None means "no filter", so an empty condition list works without a special case. For many values on one column, isin is clearer and faster to build than a long chain of |.
Filters on partition columns and data columns
You write the same kind of expression for both. The difference is what PyArrow can do with it.
- A condition on a partition column such as
yearcan be decided from the directory name alone. A fragment that cannot match is never opened. - A condition on a data column such as
amountcan use the min and max statistics stored in each Parquet row group. Row groups that cannot match are skipped. - Whatever remains is checked row by row.
Mixing both kinds in one & expression is normal and gives the best result. A condition joined with | across a partition column and a data column limits pruning, because a fragment can only be skipped if the whole expression is known to be false for it.
Common mistakes
- Using
and,orornotinstead of&,|and~. - Leaving out parentheses around each comparison.
- Comparing a string partition field with an integer, or the reverse.
- Expecting
~to keep null rows. - Referring to a partition column that was not part of the partition schema when the dataset was opened. The field does not exist, and the scan fails.
Exercise
A dataset has a nullable amount column. You want every row where amount is not greater than 100, including rows where amount is null. Write the filter expression and explain why ~(ds.field("amount") > 100) alone is not enough.
Show answer
Use ~(ds.field("amount") > 100) | ds.field("amount").is_null(). For a null amount, amount > 100 is null, and negating null gives null. A filter keeps only rows where the expression is true, so the null rows are dropped unless is_null() adds them back. Equivalent: (ds.field("amount") <= 100) | ds.field("amount").is_null().
Exercise
This filter returns the wrong rows: ds.field("year") == 2024 & ds.field("country") == "DE". Name the problem and give the corrected version.
Show answer
Python gives & higher precedence than ==, so the expression is not parsed as two comparisons joined by "and". Add parentheses: (ds.field("year") == 2024) & (ds.field("country") == "DE").