Aggregates¶
API Documentation
Aggregation is a transform like any other: build the target
model with its constructor. Mark the group keys with .group() and give every other
column an aggregate function; the constructor runs it as groupBy(...).agg(...).
Models
import typespark as ts
import typespark.functions as tsf
class Sale(ts.DataFrame):
shop: ts.String
product: ts.String
amount: ts.Double
quantity: ts.Int
class ShopTotal(ts.DataFrame):
shop: ts.String
revenue: ts.Double
units: ts.Long
products: ts.Array[ts.String]
totals = ShopTotal(
sales,
shop=sales.shop.group(), # group key
revenue=tsf.sum(sales.amount), # Double
units=tsf.sum(sales.quantity), # Long: sum of Int
products=tsf.collect_set(sales.product), # Array[String]
)
Aggregate functions return typed columns, so the target types are checked: tsf.sum of
an Int is a Long, tsf.avg is a Double, tsf.collect_set of a String is an
Array[String]. tsf.max and tsf.min work on structs too.
Global aggregates¶
Without any .group(), the aggregates run over the whole DataFrame and the result has
one row:
Model
class Totals(ts.DataFrame):
revenue: ts.Double
sales: ts.Long
# One row: no group keys
totals = Totals(
sales,
revenue=tsf.sum(sales.amount),
sales=tsf.count(sales.amount),
)
Expressions¶
A group key can be any expression: transform the column, then call .group() on the
result. Aggregates can be wrapped in functions such as tsf.round or tsf.coalesce:
key = tsf.upper(sales.shop) # transform the key, then group
total = tsf.coalesce(tsf.sum(sales.amount), ts.Double(0.0))
revenue = ShopRevenue(
sales,
shop=key.group(),
revenue=tsf.round(total, 2),
)
A group column itself is only a marker: arithmetic or comparisons on it raise
TypeError. Once the DataFrame is built, its columns are regular typed columns.
Rules¶
- Every column is either a group key or an aggregate. A plain column in an aggregating
constructor is not part of the result, and the constructor reports it as missing
(
MissingColumnError). - Group keys need at least one aggregate:
.group()alone raisesValueError. - Grouping and exploding an array can't happen in one constructor.
To derive a column from several aggregates, such as a ratio, aggregate first and compute it in a second step:
Models
class ShopSums(ts.DataFrame):
shop: ts.String
revenue: ts.Double
units: ts.Long
class ShopPrice(ts.DataFrame):
shop: ts.String
avg_unit_price: ts.Double
def avg_unit_price(sales: Sale) -> ShopPrice:
sums = ShopSums(
sales,
shop=sales.shop.group(),
revenue=tsf.sum(sales.amount),
units=tsf.sum(sales.quantity),
)
return ShopPrice(
sums,
shop=sums.shop,
avg_unit_price=sums.revenue / ts.Double(sums.units),
)
Aggregates over a window¶
An aggregate with .over(window) is a regular column: it keeps every row instead of
grouping. See Window functions.