Sub topic 8
Creating, writing, and merging feature data
This chapter assumes you can run PySpark in a Databricks notebook, know Delta tables, and understand catalog.schema.table names in Unity Catalog. It covers how to create a feature table and how to keep it current.
A feature table is a Delta table with a primary key
In Unity Catalog, a feature table is a Delta table that has a primary key constraint on non-null key columns. You can create one with plain SQL:
CREATE TABLE main.ml.product_features (
product_id BIGINT NOT NULL,
category STRING,
avg_rating DOUBLE,
CONSTRAINT product_features_pk PRIMARY KEY (product_id)
);Most pipelines create the table from a DataFrame instead, using FeatureEngineeringClient.
Creating a table from a DataFrame
Start with a DataFrame of computed features, one row per key.
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"),
)
)Then pass it to create_table. The client takes the schema from the DataFrame, marks the key columns as non-null, adds the primary key, and writes the rows.
from databricks.feature_engineering import FeatureEngineeringClient
fe = FeatureEngineeringClient()
fe.create_table(
name="main.ml.user_features",
primary_keys=["user_id"],
df=user_features_df,
description="Per-user order features over the last 90 days",
)Updating with merge
Later runs should refresh the values without duplicating keys. write_table with mode="merge" updates rows whose key already exists and inserts rows with new keys.
fe.write_table(
name="main.ml.user_features",
df=user_features_df,
mode="merge",
)Merge never deletes. A user who has no orders in the last 90 days won't appear in the aggregation, so their old row keeps its stale values. Handle this deliberately, for example by computing features for every known user and filling missing counts with 0.
Merge versus overwrite
| Mode | Effect | Use when |
|---|---|---|
| `merge` | Upserts rows by primary key. Other rows stay. | Incremental or regular refreshes. |
| `overwrite` | Replaces the whole table contents. | You recompute every row and want removed keys gone. |
Check the overwrite behavior against your workspace's Databricks Runtime documentation before relying on it in production.
Common errors
- Null or duplicate keys. Primary key columns must be non-null. Duplicate keys in the incoming DataFrame make the merge ambiguous, so run
dropDuplicates(["user_id"])or aggregate first. - Schema mismatch. The DataFrame must contain the primary key columns. Column names and types should match the table, so cast before writing.
- Missing permissions. You need
CREATE TABLEon the schema to create the table, and write access to the table to update it.
Exercise
Your nightly job recomputes 90-day order features. A user stopped ordering 100 days ago and no longer appears in the aggregation. After a merge write, what does the feature table hold for that user, and how could you avoid a stale value?
Show answer
The old row stays unchanged, because merge only updates or inserts and never deletes. To avoid the stale value, compute features for all known users (for example by left-joining the user list to the aggregation and filling counts with 0), or use overwrite mode if you recompute every row.