Sub topic 2
Choosing Primary Keys and Time Series Columns
This chapter assumes basic PySpark DataFrame operations, Delta tables, Unity Catalog names, and model training workflows.
Choosing the key
A primary key identifies one feature row. For a current-state feature table, use the entity identifier, such as user_id or product_id. Each key must identify at most one row, and key columns must be non-null.
A time series column records when a feature value was valid. For historical features, use a composite key such as user_id and feature_ts. This allows several rows for one user, provided each timestamp is different.
| Table type | Primary key | Example use |
|---|---|---|
| Current state | `user_id` | Latest customer features |
| Historical | `user_id`, `feature_ts` | Features available at past events |
Creating and updating feature data
The following example assumes user_features_df contains one row per user_id.
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",
)
fe.write_table(
name="main.ml.user_features",
df=user_features_df,
mode="merge",
)merge updates rows with existing keys and inserts new keys. Use overwrite only when the DataFrame is a complete replacement and replacing all existing rows is intended.
Defining lookups and training sets
A feature lookup describes which table and key supply features. A training set combines labeled rows with those features.
from databricks.feature_engineering import FeatureLookup
labels_df = spark.table("main.ml.churn_labels")
lookup = FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d", "avg_order_amount_90d"],
lookup_key="user_id",
)
training_set = fe.create_training_set(
df=labels_df,
feature_lookups=[lookup],
label="label",
exclude_columns=["user_id"],
)
training_df = training_set.load_df()For historical data, set timestamp_lookup_key="event_ts". The lookup then selects the latest feature value available at or before each event timestamp, preventing future information from entering training data.
Exercise
Which key should a historical user feature table use when it stores multiple snapshots per user?
Show answer
Use a composite key such as userid and featurets, and declare feature_ts as the time series column.