Sub topic 8
Creating, writing, and merging feature data
This chapter assumes you can write PySpark DataFrame code and know that a Unity Catalog table has a three-part name (catalog.schema.table). It also assumes you have seen what a feature table is and how primary keys are chosen. Here you will create a feature table, load it for the first time, and keep it current with merge and overwrite writes.
What you are creating
A Unity Catalog feature table is a Delta table with a primary key constraint on one or more non-null columns. The feature engineering client adds convenience on top of that. It creates the table, enforces the key, and applies updates with the right semantics.
You can create the table in two ways. Use the Python client when your features already exist as a DataFrame. Use plain SQL when you want to define the schema first.
Creating a table from a DataFrame
create_table does two things in one call. It derives the schema from the DataFrame and writes the DataFrame rows as the first data.
from pyspark.sql import functions as F
from databricks.feature_engineering import FeatureEngineeringClient
fe = FeatureEngineeringClient()
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"),
)
)
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",
)Things to know about this call:
- The
namemust be a full three-part Unity Catalog name. You needCREATE TABLEon the schema andUSE SCHEMAandUSE CATALOGon its parents. - Every column in
primary_keysmust be non-null. The client marks themNOT NULL, so rows with a null key make the creation fail. create_tablefails if the table already exists. It is a one-time setup step, not a re-runnable one.- The
descriptionis stored as the table comment, and people see it when they browse features.
Creating an empty table from a schema
Sometimes the table must exist before any data does, for example when a pipeline job will fill it. Pass a schema instead of a DataFrame.
from pyspark.sql.types import StructType, StructField, LongType, StringType, DoubleType
schema = StructType([
StructField("product_id", LongType(), False),
StructField("category", StringType(), True),
StructField("avg_rating", DoubleType(), True),
])
fe.create_table(
name="main.ml.product_features",
primary_keys=["product_id"],
schema=schema,
description="Per-product catalog features",
)Use df or schema, not both. The primary key field is declared nullable=False.
Creating a table with SQL
Because a feature table is a Delta table with a key constraint, SQL works too.
CREATE TABLE main.ml.product_features (
product_id BIGINT NOT NULL,
category STRING,
avg_rating DOUBLE,
CONSTRAINT product_features_pk PRIMARY KEY (product_id)
);Either way, the result is the same kind of object. Primary key constraints in Unity Catalog are informational. They are not enforced for uniqueness, so duplicate keys are your responsibility. The next sections show why that matters.
Writing and merging data
After creation, you load new data with write_table. It takes a mode, and the mode decides what happens to rows that already exist.
fe.write_table(
name="main.ml.user_features",
df=user_features_df,
mode="merge",
)| Mode | Matching key | New key | Rows missing from the DataFrame |
|---|---|---|---|
| `merge` | Row is updated | Row is inserted | Left untouched |
| `overwrite` | Replaced | Replaced | Removed |
merge is the default and the right choice for most recurring jobs. It acts as an upsert (update plus insert): existing keys get their new feature values, and new keys are added.
overwrite replaces the whole table contents with the DataFrame. Use it for a full rebuild, or when you intentionally want entities that no longer appear to disappear. If a job computes only a subset of users and you overwrite, every other user is deleted from the table.
diagram mermaid
caption: How write_table treats existing and new keys in merge mode
alt: Flowchart showing each incoming row compared with the table by primary key. A matching key leads to an update, and a missing key leads to an insert. Rows in the table that are absent from the input stay unchanged.
flowchart TD
A[Incoming DataFrame row] --> B{Primary key exists in table?}
B -- Yes --> C[Update feature values]
B -- No --> D[Insert new row]
E[Table rows not in DataFrame] --> F[Left unchanged]Time series feature tables
If the table has a time series column, the timestamp is part of the primary key. A merge then matches on the full key, so a new timestamp for the same user is a new row, not an update.
fe.create_table(
name="main.ml.user_activity_features",
primary_keys=["user_id", "feature_ts"],
timeseries_columns=["feature_ts"],
df=activity_features_df,
)This is what lets you keep a history of feature values and look them up as of a point in time later. A daily job that writes the same feature_ts twice overwrites that day's row, and a job that writes a new feature_ts adds a row.
Avoiding duplicate keys
A merge needs at most one source row per key. If the incoming DataFrame has two rows for the same user_id, Delta cannot decide which one to apply, and the write typically fails with a multiple-matches error. Because the primary key is not enforced on plain writes, a bad create_table source could also store duplicates.
Check and deduplicate before you write:
from pyspark.sql import Window
w = Window.partitionBy("user_id").orderBy(F.col("last_order_ts").desc())
deduped_df = (
user_features_df
.withColumn("rn", F.row_number().over(w))
.filter("rn = 1")
.drop("rn")
)
assert deduped_df.count() == deduped_df.select("user_id").distinct().count()
fe.write_table(name="main.ml.user_features", df=deduped_df, mode="merge")Use row_number with an explicit ordering rather than dropDuplicates. dropDuplicates keeps an arbitrary row, which makes results differ between runs.
Schema changes
The DataFrame you write should have the table's columns with compatible types. A column name that does not exist in the table is a common failure. When you add a new feature, first add the column to the table, then include it in the DataFrame.
ALTER TABLE main.ml.user_features ADD COLUMNS (distinct_categories_90d BIGINT);Existing rows hold null for the new column until the next merge fills it. A model that expects the column must handle nulls, as covered in the chapter on missing values. Renaming or dropping a feature column that a logged model uses breaks that model's lookups, so treat feature column names as a contract.
Common errors
- Table already exists. You called
create_tablein a job that runs repeatedly. Move creation to a setup step, and let the recurring job callwrite_table. - Null primary key. Filter out rows where a key column is null before creating or writing.
- Multiple source rows match. Deduplicate on the full primary key, including the timestamp for time series tables.
- Accidental data loss.
overwriteon a partial DataFrame deletes the rest. Default tomergeunless you mean a full rebuild. - Permission denied. Writing needs
MODIFYandSELECTon the table, and creating needsCREATE TABLEon the schema.
Exercise
A nightly job recomputes features only for users who ordered in the last day, then calls write_table with mode="overwrite". After a week, the table has only a small fraction of its earlier users, and a model's batch scoring returns null features for most of them. What went wrong, and what is the fix?
Show answer
Overwrite replaces the entire table with the DataFrame, so every user who did not order that day was deleted each night. Switch the job to mode="merge", which updates users present in the DataFrame, inserts new ones, and leaves all other users unchanged. Then rebuild the lost rows with a full recomputation, and make sure the DataFrame has one row per user_id before merging.