Sub topic 9
Defining feature lookups
A feature lookup tells Databricks which features to read from a feature table and which column in your data to use as the join key. This chapter covers the FeatureLookup object, its main parameters, and the mistakes people most often make with it.
Prerequisites
This chapter assumes you can:
- Write PySpark DataFrame code and read Delta tables.
- Use Unity Catalog three-level names (
catalog.schema.table). - Read a feature table that already exists, such as
main.ml.user_featuresfrom the earlier chapters on feature tables and primary keys.
What a lookup is
A feature table stores one row per primary key. A labeled DataFrame stores one row per training example. To train a model, you join the two on the key.
You could write that join by hand with df.join(...). A FeatureLookup records the same join as metadata instead. It names the table, the features, and the key. The metadata is useful for two reasons:
create_training_setuses it to build the training DataFrame.log_modelstores it with the model, so scoring can repeat the same join later without extra code.
A lookup does not read any data when you create it. It is a plain description. Data is read only when you build a training set and call load_df().
The basic lookup
The example below selects two features from main.ml.user_features and joins them on user_id.
from databricks.feature_engineering import FeatureEngineeringClient, FeatureLookup
fe = FeatureEngineeringClient()
labels_df = spark.table("main.ml.churn_labels") # user_id, label
feature_lookups = [
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=feature_lookups,
label="label",
exclude_columns=["user_id"],
)
training_df = training_set.load_df()Key parameters
| Parameter | Purpose |
|---|---|
| `table_name` | Full Unity Catalog name of the feature table. |
| `feature_names` | Features to retrieve. If you leave it out, all non-key columns are returned. |
| `lookup_key` | Column in your DataFrame that matches the table's primary key. |
| `timestamp_lookup_key` | Column in your DataFrame used for point-in-time lookups on time series tables. |
| `rename_outputs` | Dictionary that renames returned features to avoid name clashes. |
Choosing features
Pass feature_names explicitly. Without it, the lookup returns every non-key column. Then a teammate who adds a column to the feature table changes your training data without any change to your code. An explicit list keeps the training set stable.
Matching the lookup key
lookup_key names a column in your labeled DataFrame. It does not have to share a name with the primary key in the feature table. If the feature table uses user_id and your labels use customer_id, set lookup_key="customer_id".
For a composite primary key, pass a list. The order must match the order of the primary key columns in the feature table.
FeatureLookup(
table_name="main.ml.store_product_features",
feature_names=["units_sold_7d"],
lookup_key=["store_id", "product_id"],
)The key types in your DataFrame must be compatible with the table's key types. A string user_id against a bigint key can fail or match nothing, depending on how Spark casts it. Cast the column before you build the training set.
Combining several feature tables
A model often needs features from more than one table. Add one lookup per table.
feature_lookups = [
FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d", "avg_order_amount_90d"],
lookup_key="user_id",
),
FeatureLookup(
table_name="main.ml.product_features",
feature_names=["category", "avg_rating"],
lookup_key="product_id",
),
]Each lookup can use a different key column. The labeled DataFrame must contain every key column that the lookups use. In this example it needs both user_id and product_id.
Handling name clashes with rename_outputs
Two feature tables can contain columns with the same name, such as avg_rating. A clash also happens when a feature has the same name as a column already in your labeled DataFrame. Use rename_outputs to give the returned feature a new name.
FeatureLookup(
table_name="main.ml.product_features",
feature_names=["avg_rating"],
lookup_key="product_id",
rename_outputs={"avg_rating": "product_avg_rating"},
)The renamed column is the name the model sees. Logged lookup metadata carries the rename, so batch scoring produces the same name.
Lookups on time series tables
When a feature table declares a time series column, the lookup can match each row to the feature values that were current at that row's timestamp. You enable this by setting timestamp_lookup_key.
FeatureLookup(
table_name="main.ml.user_activity_features",
lookup_key="user_id",
timestamp_lookup_key="event_ts",
)Here event_ts is a column in your labeled DataFrame. The next chapters cover point-in-time correctness in detail. For now, remember the rule: if the feature table has a time series column, set timestamp_lookup_key. Leaving it out produces a different join than you intend.
What happens when a key has no match
The lookup behaves like a left join from your labeled DataFrame. Every labeled row stays in the result. If a key does not exist in the feature table, its feature columns come back as null.
This has two consequences:
- Row counts do not change, so a missing key will not raise an error.
- Your model receives nulls. Some scikit-learn estimators fail on nulls, and others silently treat them as ordinary values.
Check for this after building the training DataFrame.
from pyspark.sql import functions as F
null_rate = training_df.select(
F.avg(F.col("order_count_90d").isNull().cast("int")).alias("null_rate")
)
null_rate.show()A high null rate usually means one of three things. The feature table has not been populated for those keys. The key types do not match. Or the feature table covers only a subset of users.
Common errors
- Using a column that is not a feature. Listing a primary key in
feature_namesfails. Keys come from your DataFrame and are not features. - Typos in feature names. A name that is not in the table raises an error when you call
create_training_set, not when you create theFeatureLookup. - Missing permissions. You need
SELECTon the feature table, plusUSE CATALOGandUSE SCHEMAon its parents. Without these, the call fails with a permissions error. - Forgetting
exclude_columns. If you leave the key in the training DataFrame, the model may train onuser_idas if it were a feature. Exclude it unless you intend otherwise. - Unstable
feature_names. Relying on the default means the training set changes when the table schema changes.
A reviewing checklist
Before you build a training set from your lookups, confirm that:
- Each
table_nameis a full three-level name. feature_namesis listed explicitly.- Every
lookup_keyexists in the labeled DataFrame with a compatible type. - Tables with a time series column have a
timestamp_lookup_key. - Name clashes are resolved with
rename_outputs. - Key columns that are not features are removed with
exclude_columns.
Exercise
Your labeled DataFrame has columns customerid, storeid, and label. The feature table main.ml.customerfeatures has primary key userid and a feature named lifetimevalue. Write the FeatureLookup, and explain what you would check if the training DataFrame comes back with all lifetimevalue values null.
Show answer
Use FeatureLookup(tablename="main.ml.customerfeatures", featurenames=["lifetimevalue"], lookupkey="customerid"). The lookup key names the column in your DataFrame, so it can differ from the table's primary key name. If every value is null, check that the customerid type matches the type of userid in the feature table, that the feature table contains rows for those IDs, and that the values are formatted the same way (for example, no padding or case differences).
Exercise
Why should you pass feature_names explicitly instead of relying on the default?
Show answer
Without feature_names the lookup returns every non-key column. If someone adds a column to the feature table, your training data changes without any change to your code. An explicit list keeps the training set stable and makes the model's inputs clear to readers.