Sub topic 14
Window functions
This chapter covers window functions in Spark DataFrames. It assumes you can already read data into a DataFrame, use select, withColumn and filter, and run a groupBy aggregation. It also assumes you know the orders DataFrame from the earlier chapters, with columns order_id, customer, order_date and amount.
Why window functions exist
A groupBy aggregation collapses many rows into one row per group. Sometimes you want a group-level calculation but still need every original row. Examples include a running total, the rank of an order within a customer, or the previous order's amount next to the current one.
A window function does this. It computes a value for each row by looking at a set of related rows, called the window, and it keeps every input row in the result.
| Operation | Rows returned | Typical use |
|---|---|---|
| `groupBy().agg()` | One per group | Totals and averages per group |
| Window function | One per input row | Running totals, rankings, comparisons with neighbouring rows |
The window specification
You describe a window with the Window class from pyspark.sql. A specification has up to three parts.
partitionBysplits the rows into independent groups. A window never looks across partitions.orderBysorts the rows inside each partition. Ranking and offset functions need it.- A frame (
rowsBetweenorrangeBetween) picks which rows around the current row take part in the calculation.
You then apply a function to the specification with .over(...).
from pyspark.sql import Window
from pyspark.sql import functions as F
w = Window.partitionBy("customer").orderBy("order_date")
running = orders.withColumn("running_total", F.sum("amount").over(w))
display(running)For each customer, rows are sorted by order_date. The running_total column holds the sum of amount from that customer's first order up to the current row. Alice's second order shows 150.0 (120.0 plus 30.0). All four input rows are still present.
The amount for Carol is null, and sum skips nulls. Her running total is therefore null, because the only value in her frame is null.
Aggregates, ranking and offset functions
Window functions fall into three families.
- Aggregate functions such as
sum,avg,min,maxandcount. These are the same functions you use withgroupBy, now used with.over(). - Ranking functions:
row_number,rank,dense_rank,ntileandpercent_rank. - Offset functions:
lagandlead, which read a value from a row before or after the current one.
The next example uses one ranking function and one offset function together.
w = Window.partitionBy("customer").orderBy("order_date")
enriched = (
orders
.withColumn("order_number", F.row_number().over(w))
.withColumn("previous_amount", F.lag("amount", 1).over(w))
.withColumn("change", F.col("amount") - F.col("previous_amount"))
)
display(enriched)row_number() numbers the rows 1, 2, 3 within each customer. lag("amount", 1) returns the amount from one row earlier in the same partition. The first row of each partition has no earlier row, so lag returns null there. You can pass a third argument as a default, for example F.lag("amount", 1, 0.0).
Ties: row_number, rank and dense_rank
These three functions differ only when two rows have the same value in the orderBy column.
| Function | Behaviour on ties | Example result for values 10, 10, 8 |
|---|---|---|
| `row_number` | Gives distinct numbers, picking an arbitrary order among ties | 1, 2, 3 |
| `rank` | Ties share a rank, and the next rank is skipped | 1, 1, 3 |
| `dense_rank` | Ties share a rank, and no rank is skipped | 1, 1, 2 |
If ties matter, add a second sort column to make the order deterministic. Otherwise row_number can return different results between runs.
Frames: which rows are in the window
The frame sets the rows that an aggregate function sees. Two defaults catch many people out.
- If you give an
orderByand no frame, the frame runs from the start of the partition to the current row, including peers with equal ordering values. This is why the first example produced a running total. - If you give no
orderBy, the frame is the whole partition.
You can set the frame yourself. Offsets are relative to the current row, with 0 meaning the current row.
w3 = (
Window.partitionBy("customer")
.orderBy("order_date")
.rowsBetween(-2, 0)
)
moving = orders.withColumn("avg_last_3_orders", F.avg("amount").over(w3))
display(moving)rowsBetween(-2, 0) counts physical rows: the two rows before the current one, plus the current one. rangeBetween works on the values of the ordering column instead, so it needs a numeric or date-like ordering expression, and rows with equal values are treated as one position. Use Window.unboundedPreceding and Window.unboundedFollowing for open ends.
w_all = Window.partitionBy("customer")
share = orders.withColumn(
"customer_total", F.sum("amount").over(w_all)
).withColumn(
"share_of_customer", F.col("amount") / F.col("customer_total")
)
display(share)This version has no orderBy, so every row sees its customer's whole partition. It is a convenient way to put a group total next to each detail row without a join.
A common pattern: the latest row per group
Window functions are the standard way to keep one row per group, such as each customer's most recent order. Number the rows in descending order, then filter.
w_latest = Window.partitionBy("customer").orderBy(F.col("order_date").desc())
latest = (
orders
.withColumn("rn", F.row_number().over(w_latest))
.filter(F.col("rn") == 1)
.drop("rn")
)
display(latest)You cannot filter on a window expression directly in the same step, so the pattern creates the column first and filters on it afterwards.
How it runs, and what it costs
Spark must bring all rows with the same partitionBy values onto the same task, and sort them. In the query plan this shows up as an Exchange (a shuffle) followed by a Sort and a Window node. You can check this with explain().
running.explain()Three failure modes follow from this design.
- No
partitionBy. Spark must put all rows into a single partition to sort them. On a large table this is slow and can run out of memory. Spark logs a warning about moving all data to a single partition. Add apartitionByunless you truly need a global order. - Skewed partition keys. If one customer owns most rows, one task does most of the work. Choose a partition key with an even spread.
- Several windows with different specifications. Each distinct
partitionByandorderBypair can trigger its own shuffle and sort. Reuse one specification across columns where you can, asenricheddid above.
Window functions in SQL
The same logic works in SQL through a temporary view, which suits teams that prefer SQL.
orders.createOrReplaceTempView("orders_v")
sql_running = spark.sql("""
SELECT customer, order_date, amount,
SUM(amount) OVER (
PARTITION BY customer ORDER BY order_date
) AS running_total
FROM orders_v
""")
display(sql_running)Both forms compile to the same plan, so choose the one that reads better to you.
Summary of the main points
- A window function adds a computed column and keeps all rows.
partitionBysets the groups,orderBysets the sequence, and the frame sets the rows included.- Use
row_number,rankanddense_rankfor rankings, andlagandleadfor neighbouring rows. - Filter on a ranking column in a separate step to keep one row per group.
- Windows cost a shuffle and a sort. Always partition, and watch for skew.
Exercise
Using the orders DataFrame, write code that adds a column order_rank ranking each customer's orders by amount from largest to smallest, with ties sharing a rank and no gaps after ties. Which function do you use, and what happens to Carol's null amount in the ordering?
Show answer
Use dense_rank with a window partitioned by customer and ordered by amount descending:
w = Window.partitionBy("customer").orderBy(F.col("amount").desc())
ranked = orders.withColumn("orderrank", F.denserank().over(w))
Spark sorts nulls first in descending order by default (for desc(), nulls come last; for asc(), nulls come first). With F.col("amount").desc() the null sorts last, so a null amount gets the lowest rank in its partition. Carol has only one order, so her rank is 1. To control null placement explicitly, use F.col("amount").desc_nulls_last().
Exercise
A teammate writes Window.orderBy("order_date") with no partitionBy and applies row_number() to a table with 500 million rows. What problem will occur, and how do you fix it?
Show answer
With no partitionBy, Spark moves all rows into a single partition to sort them. That makes one task do all the work, which is slow and can fail with out-of-memory errors. Fix it by adding a partitionBy on a column that splits the data into many balanced groups, if the logic allows it. If a global order is truly required, consider whether a plain orderBy plus another approach would meet the need.