Sub topic 2
Computing features from raw tables with Spark
This chapter assumes you can write basic PySpark DataFrame code, work in a Databricks notebook, and read tables by their catalog.schema.table names. It covers turning a raw event table into one row of features per entity. The next chapters cover storing those rows in a feature table.
From raw rows to one row per entity
Raw tables record events: one row per order, click, or payment. Models usually need one row per entity, such as a user. A feature is a column on that row that describes the entity's behavior. Aggregation produces these columns. You group by the entity key and summarize each group.
The example below reads an orders table. It keeps the last 90 days and computes three features per user.
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
user_features_df = (
orders
.filter(F.col("order_ts") >= F.date_sub(F.current_date(), 90))
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.avg("amount").alias("avg_order_amount_90d"),
F.max("order_ts").alias("last_order_ts"),
)
)The result has one row per user_id. That column will later become the primary key of the feature table, so each value must appear only once.
Design choices that matter
- Name the window. The suffix
_90dstates what the number means. A column calledorder_counthides the window, and people will misuse it. - Filter before grouping. Spark can then skip data it does not need, and the aggregate covers only the intended period.
- Keep the key unique. If you join or explode before grouping, check that the output still has one row per key.
- Expect nulls.
avgover a user with no qualifying rows is not computed, because that user is absent from the result. Users with no orders in the window will have no row at all. Decide later how to treat them, for example by fillingorder_count_90dwith 0 after a join.
Check the output before storing it
Verify the one-row-per-key assumption before you write anything.
total_rows = user_features_df.count()
distinct_users = user_features_df.select("user_id").distinct().count()
assert total_rows == distinct_users, "Duplicate user_id rows in features"
user_features_df.show(5)A common error is a groupBy on the wrong column, such as order_id. That returns one row per order and fails this check.
Exercise
A teammate computes F.avg("amount") grouped by user_id over all orders ever, and names the column avg_order_amount. Give two problems with this feature, and the change you would make to the code.
Show answer
The name hides the time window, and an all-time average changes meaning as history grows, so values from different dates are not comparable. It also gives old behavior the same weight as recent behavior. Add a filter such as F.col("order_ts") >= F.date_sub(F.current_date(), 90) before groupBy, and rename the column to avg_order_amount_90d.