Skip to content

Generators

API Documentation

typespark.Array.explode
typespark.functions.explode
typespark.functions.explode_outer

A generator turns one row into several. explode is the common one: one row per element of an array.

In Spark, the column a generator produces can't be used in the select that creates it. To read fields of an exploded struct you write two steps by hand: explode under an alias, then select from the alias.

exploded = raw.select(
    "building_id", F.explode("areas").alias("area")
)
flat = exploded.select(
    "building_id",
    F.col("area.id").alias("area_id"),
    F.round("area.value", 2).alias("value"),
)

TypeSpark lets you write it as one transform and splits it into those steps for you.

explode(access)

Array[T].explode() explodes an array column. With an access function it returns whatever you build from the element, so the target model gets typed columns straight from the exploded rows:

Models
import typespark as ts
import typespark.functions as tsf


class Area(ts.Struct):
    id: ts.String
    value: ts.Double


class Building(ts.DataFrame):
    building_id: ts.String
    areas: ts.Array[Area]


class BuildingArea(ts.DataFrame):
    building_id: ts.String
    area_id: ts.String
    value: ts.Double
def flatten(df: Building) -> BuildingArea:
    return BuildingArea(
        df,
        building_id=df.building_id,
        area_id=df.areas.explode(lambda a: a.id),
        value=df.areas.explode(lambda a: tsf.round(a.value, 2)),
    )

Without access, it returns the element itself, as a typed column:

Model
class BuildingAreaStruct(ts.DataFrame):
    building_id: ts.String
    area: Area
flat = BuildingAreaStruct(
    df,
    building_id=df.building_id,
    area=df.areas.explode(),  # the element itself: an Area
)

The element only exists once the explode has run, so access to it is deferred: put the whole expression inside access. Reading a field off the bare element raises ExplodeAccessError, pointing you to the access form:

area_id=df.areas.explode().id  # ExplodeAccessError
area_id=df.areas.explode(lambda a: a.id)  # ok

How it runs

This is the one place where TypeSpark shapes the query instead of passing one call straight to Spark. The constructor runs the transform in two selects:

  1. Explode the array under an internal alias (__ts_explode_<n>), next to the source columns.
  2. Evaluate the target columns against the exploded rows.

The logical plan has one projection more than the hand-written version, but Spark's optimizer folds it away. For the example above, the optimized plan is the same as for the hand-written code:

Project [building_id,
         __ts_explode_0.id AS area_id,
         round(__ts_explode_0.value, 2) AS value]
+- Generate explode(areas), [1], false, [__ts_explode_0]
   +- Filter ((size(areas) > 0) AND isnotnull(areas))
      +- LogicalRDD [building_id, areas]

Both explode(...) calls on areas share one Generate: the array is exploded once.

Rules

  • Every explode() on the same array shares one explode, however many columns use it.
  • Only one array can be exploded per DataFrame: exploding two raises ExplodeAccessError.
  • Exploding and grouping can't happen in one constructor.
  • explode(...) builds model columns, so it belongs in the constructor. In withColumn it raises ExplodeAccessError; use tsf.explode there.

tsf.explode and tsf.explode_outer

tsf.explode and tsf.explode_outer are the plain Spark generators with typed results: the element type of the array. Use them where Spark handles the generator itself, such as withColumn or select:

# One row per area; the result is a plain ts.DataFrame
rows = df.withColumn("area", tsf.explode(df.areas))

As in Spark, the exploded column can't be read from in the same step.

Not supported yet

posexplode, inline, stack and json_tuple, an outer variant of explode(access), and exploding maps.