Skip to content

Functions

typespark.functions mirrors pyspark.sql.functions (aggregates, string, math, date/time, array, higher-order, window) but takes and returns typed columns, so the result type is tracked:

import typespark.functions as tsf

oldest = tsf.max(person.age)  # typed column, still Int
n = tsf.count(person.name)  # typed column, Long

See the API Documentation for the full list, by module.

Units, formats and days

Some Spark functions take a unit, format or day as a string, and Spark only accepts a fixed set of them. TypeSpark types those arguments as Literals, so a misspelling is a type error instead of a null at runtime:

Model
class Shipment(ts.DataFrame):
    ordered_at: ts.Timestamp
    shipped_at: ts.Timestamp
    order_date: ts.Date
month = tsf.date_trunc("MONTH", s.ordered_at)  # Timestamp
# Int: whole days between the two
days = tsf.timestamp_diff("DAY", s.ordered_at, s.shipped_at)
monday = tsf.next_day(s.order_date, "MONDAY")  # Date
tsf.date_trunc("MONTHS", s.ordered_at)  # type error: not a format
tsf.next_day(s.order_date, "Mon")  # type error: days are uppercase
Type Used by Values
tsf.TimeUnit tsf.timestamp_diff YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE, SECOND, MILLISECOND, MICROSECOND
tsf.TimestampAddUnit tsf.timestamp_add TimeUnit, plus DAYOFYEAR
tsf.TruncFormat tsf.trunc YEAR, YYYY, YY, QUARTER, MONTH, MON, MM, WEEK
tsf.DateTruncFormat tsf.date_trunc TruncFormat, plus DAY, DD, HOUR, MINUTE, SECOND, MILLISECOND, MICROSECOND
tsf.DayOfWeek tsf.next_day MO/MON/MONDAY through SU/SUN/SUNDAY
ts.JoinType DataFrame.join see Join types

Spark itself is case-insensitive here; TypeSpark takes the spelling Spark documents: uppercase for units, formats and days, lowercase for join types.

Use the types in your own signatures to pass a value through:

import typespark.functions as tsf


def truncate(
    s: Shipment, unit: tsf.DateTruncFormat
) -> ts.Timestamp:
    return tsf.date_trunc(unit, s.ordered_at)

Spark 4 functions

A few typed functions wrap features PySpark 3.5 lacks. TypeSpark doesn't emulate them on 3.5: calling one there raises ts.UnsupportedSparkFeatureError, naming the feature and the Spark version it needs.

Function Needs
tsf.ltrim / tsf.rtrim with trim Spark 4.0
tsf.ceil / tsf.floor with scale Spark 4.0
tsf.array_position Spark 4.0
tsf.array_remove Spark 4.0
tsf.timestamp_add Spark 4.0