Skip to content

Transforms

API Documentation

typespark.DataFrame

A transform is a function from one model to another:

Models
import typespark as ts
import typespark.functions as tsf


class Order(ts.DataFrame):
    order_id: ts.String
    customer_id: ts.String
    amount: ts.Double
    status: ts.String


class OrderReport(ts.DataFrame):
    order_id: ts.String
    amount_rounded: ts.Double
    is_large: ts.Bool
def report(orders: Order) -> OrderReport:
    return OrderReport(
        orders,
        order_id=orders.order_id,
        amount_rounded=tsf.round(orders.amount, 2),
        is_large=orders.amount > 1000,
    )

The signature is the contract. report takes an Order and returns an OrderReport, and the type checker holds it to that: a missing or misspelled target column, a wrong column type, or a column the source doesn't have is an error before Spark runs.

The constructor is the mapping

Calling a model with a source DataFrame and one keyword per column builds the target from the source. Each keyword is aliased to its target column name, and the result is checked against the model as it's built. The raw PySpark equivalent needs a manual .alias() per column, and nothing checks the names or types:

orders.select(
    orders["order_id"].alias("order_id"),
    F.round(orders["amount"], 2).alias("amount_rounded"),
    (orders["amount"] > 1000).alias("is_large"),
)

The split keeps the two sides decoupled:

  • The target model says what: the columns, their types, defaults and metadata. It doesn't mention any source.
  • The constructor call says how, from this particular source. It is the only place that knows both models.

When a source column is renamed or retyped, the error points at the mapping line, and the target schema, and everything downstream of it, stays as it is. One target can be built from several sources, each with its own mapping.

The source can be any typed DataFrame, including a filtered or joined one: OrderReport(orders.filter(...), ...).

Depend on the columns you use

A transform only needs the columns it reads. Type its input with a model that has just those, and any model that inherits from it fits:

class Contact(ts.DataFrame):
    name: ts.String
    email: ts.String


class Customer(Contact):
    customer_id: ts.String


class Supplier(Contact):
    supplier_id: ts.String
    country: ts.String


class MailingListEntry(ts.DataFrame):
    name: ts.String
    email: ts.String


def mailing_list(contacts: Contact) -> MailingListEntry:
    return MailingListEntry(
        contacts,
        name=contacts.name,
        email=tsf.lower(contacts.email),
    )
mailing_list(customers)  # a Customer is a Contact
mailing_list(suppliers)  # so is a Supplier

The base model works as an interface: mailing_list doesn't know about customers or suppliers, and a new source only has to inherit Contact.

A model doesn't have to describe the whole table. Wrapping a wide DataFrame with from_df() keeps only the model's columns, so the transform never sees the rest:

crm = spark.read.table("crm.customers")  # dozens of columns
contacts = Contact.from_df(crm)  # keeps name and email
entries = mailing_list(contacts)

With columnar sources such as Parquet or Delta, Spark then only reads those columns. If one of them is missing from the data, from_df() raises MissingColumnError.

Keep I/O at the edges

Read and wrap at the start, write at the end, and keep the transform itself free of I/O:

# read and wrap
orders = Order.from_df(spark.read.table("raw.orders"))

result = report(orders)  # no I/O in the transform

writer = result.to_spark().write.mode("overwrite")
writer.saveAsTable("mart.order_report")

The model also gives the target table its schema, so the table can be declared before anything is written:

def create_report_table(spark: SparkSession) -> None:
    spark.catalog.createTable(
        "mart.order_report", schema=OrderReport.generate_schema()
    )

Compose

Transforms chain because their types line up. A step that keeps the columns returns the same model:

def paid(orders: Order) -> Order:
    return orders.filter(lambda o: o.status == "paid")


def paid_report(orders: Order) -> OrderReport:
    return report(paid(orders))

filter also takes a function of the DataFrame, as above, which is handy when there is no variable to refer to.

Test

A transform is a plain function, so a test builds the input with create(), calls it, and checks the result:

def test_report_flags_large_orders(spark: SparkSession) -> None:
    orders = Order.create(
        [
            ("o1", "c1", 12.345, "paid"),
            ("o2", "c1", 5000.0, "paid"),
        ]
    )

    rows = report(orders).to_spark().orderBy("order_id").collect()

    assert [r.amount_rounded for r in rows] == [12.35, 5000.0]
    assert [r.is_large for r in rows] == [False, True]