Sub topic 7
Choosing primary keys and time series columns
This chapter assumes you can write PySpark DataFrame code and know what a Delta table is. It also assumes you can read a three-level Unity Catalog name such as main.ml.user_features. You should have seen a feature table created from a DataFrame, which the previous chapter covered. Here the focus is the one design decision that shapes every later step: which columns identify a row.
Why the key matters
A feature table is a Delta table in Unity Catalog with a primary key. That key does three jobs:
- Writes.
write_tableinmergemode matches incoming rows to existing rows by key. It updates matches and inserts the rest. - Lookups. A
FeatureLookupjoins the feature table to your labeled data using the key columns. - Serving. A model logged with its feature lookups retrieves features by key at batch and online inference time.
If the key is wrong, merges create duplicates or overwrite good rows. Joins then multiply your training rows or return the wrong values.
Rules for primary key columns
- Every key column must be
NOT NULL. - The key must identify one row. For a plain feature table, that means one row per entity, such as one row per
user_id. - Unity Catalog primary keys are informational. Databricks records the constraint but does not reject duplicate values. You are responsible for uniqueness.
The last rule is the one that causes trouble. If two rows share a key, a lookup join can return both. Your training set grows, and some labels are repeated with different feature values.
Picking the key
Choose the column, or the smallest set of columns, that names the thing you are describing. Ask what the model will have in hand at inference time. That value must be the lookup key.
| Situation | Primary key | Time series column |
|---|---|---|
| Latest snapshot of a customer profile | `user_id` | None |
| Product attributes, overwritten daily | `product_id` | None |
| Daily activity counts per user, history kept | `user_id`, `feature_ts` | `feature_ts` |
| Features per store and product | `store_id`, `product_id` | None |
Prefer stable business identifiers over row numbers or names. Composite keys are fine. Keep them as small as you can, because every consumer must supply every key column.
Declaring a snapshot table
A snapshot table keeps only the current value per entity. In SQL, write the constraint yourself:
CREATE TABLE main.ml.product_features (
product_id BIGINT NOT NULL,
category STRING,
avg_rating DOUBLE,
CONSTRAINT product_features_pk PRIMARY KEY (product_id)
);From Python, pass primary_keys and Databricks adds the constraint. The key columns in the DataFrame must not contain nulls:
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",
)A cheap guard before writing is to check for nulls and duplicates in the key:
from pyspark.sql import functions as F
key_cols = ["user_id"]
null_keys = user_features_df.filter(
" OR ".join(f"{c} IS NULL" for c in key_cols)
).count()
duplicate_keys = (
user_features_df.groupBy(*key_cols).count().filter(F.col("count") > 1).count()
)
assert null_keys == 0, "Key columns contain nulls"
assert duplicate_keys == 0, "Key columns are not unique"Time series columns
Some features change, and the model must see the value that was true at a past moment. Suppose a user had 2 sessions last week and 40 this week. A snapshot table keeps only 40. A training row labeled with last week's event would then be paired with a value from the future, which is label leakage.
To keep history, store one row per entity per time and declare the time column as a time series column. The time column is part of the primary key.
Rules for the time series column:
- It must be part of the primary key.
- It must be a timestamp or date type.
- A table can have only one.
- It must be
NOT NULL, like every key column.
This example builds a small history table and creates it:
from pyspark.sql import functions as F
from databricks.feature_engineering import FeatureEngineeringClient
fe = FeatureEngineeringClient()
activity_features_df = (
spark.createDataFrame(
[
(1, "2026-11-01 00:00:00", 2),
(1, "2026-11-08 00:00:00", 40),
(2, "2026-11-01 00:00:00", 7),
],
["user_id", "feature_ts", "sessions_7d"],
)
.withColumn("feature_ts", F.to_timestamp("feature_ts"))
)
fe.create_table(
name="main.ml.user_activity_features",
primary_keys=["user_id", "feature_ts"],
timeseries_columns=["feature_ts"],
df=activity_features_df,
description="Weekly session counts per user, one row per user per week",
)The SQL equivalent marks the time column inside the constraint:
CREATE TABLE main.ml.user_activity_features (
user_id BIGINT NOT NULL,
feature_ts TIMESTAMP NOT NULL,
sessions_7d INT,
CONSTRAINT user_activity_features_pk
PRIMARY KEY (user_id, feature_ts TIMESERIES)
);How the lookup uses the time column
Without a time column, a lookup matches on the key alone. With one, you give the lookup a timestamp column from your labeled data. For each labeled row, the join returns the most recent feature row whose time is at or before that row's timestamp.
from databricks.feature_engineering import FeatureLookup
lookup = FeatureLookup(
table_name="main.ml.user_activity_features",
lookup_key="user_id",
timestamp_lookup_key="event_ts",
)An event for user 1 at 2026-11-05 receives sessions_7d = 2, the 1 November row. It never receives 40, because that row is dated after the event. The next chapters cover lookups and training sets in detail. For now, remember that this behavior works only if the table declares its time series column.
The timestamp_lookup_key column lives in your labeled DataFrame, not in the feature table. In the example it is event_ts.
Common errors
- Null in a key column. Table creation or writes fail. Filter or fix the rows, or choose a different key.
- Duplicate keys. Nothing fails at write time. Training sets grow or contain conflicting rows. Run the uniqueness check above.
- Time column left out of the primary key. A time series column must also be listed in
primary_keys. - Time added "just in case". A time series table is larger and slower to look up than a snapshot. Use one only when you need values as of past times.
- Key not available at inference. If the model input does not have
user_idbut only an email address, the lookup cannot run. Pick the key the serving system actually has. - Wrong key type. A
STRINGkey in the table and aBIGINTkey in the labels may join by implicit cast or not at all. Match the types.
Exercise
A table stores daily avg_basket_value per store_id, one row per store per day, and you need training rows to see the value as it was on each event date. Which columns form the primary key, which column is the time series column, and which extra argument does the lookup need?
Show answer
The primary key is store_id plus the date column (for example feature_date). The date column is also declared as the time series column with timeseries_columns=["feature_date"]. The lookup needs timestamp_lookup_key set to the timestamp or date column in the labeled data, so each event receives the latest feature row at or before its own date.
Exercise
You write a DataFrame to a snapshot table keyed on user_id, and the write succeeds. Later your training set has more rows than your label table. What is the most likely cause, and how do you check for it?
Show answer
The feature table contains duplicate user_id values. Unity Catalog does not enforce primary key uniqueness, so the join returns multiple matches per label row. Group by the key columns and count, then look for counts above 1.