9. NULLs in entities¶
Reference
The reference for this topic is upload_features.
A trap in production: a NULL in an entity key column cannot be stored. About 1% of the tutorial events have no partner (a NULL partner id), so a feature keyed on the partner meets exactly this. This page shows what the framework says, then how to declare a substitute value.
import dataclasses
import getpass
import os
import tdfs4ds # importing it first also loads a .env file, if you have one
import teradataml as tdml
# 1. Open the Teradata session. Host and user come from the environment (TDFS4DS_TD_HOST,
# TDFS4DS_TD_USERNAME), the password from TDFS4DS_TD_PASSWORD or a prompt: nothing secret
# is written on this page.
host = os.environ["TDFS4DS_TD_HOST"]
user = os.environ["TDFS4DS_TD_USERNAME"]
password = os.environ.get("TDFS4DS_TD_PASSWORD") or getpass.getpass("Teradata password: ")
tdml.create_context(host=host, username=user, password=password)
# 2. Pick your industry. This is the ONLY line to change: retail, banking, healthcare, pharma,
# manufacturing, assembly, energy or transportation. Every name below comes from S.
S = tdfs4ds.tutorial_scenario("retail")
# 3. Connect to the feature store (created when missing) and choose a data domain. disposable=True
# records that this domain is an experiment, so the last page removes it in one call.
DATABASE = os.environ.get("TDFS4DS_TD_DATABASE") or user
tdfs4ds.connect(database=DATABASE, create_if_missing=True)
tdfs4ds.create_data_domain(f"TUTORIAL_{S.name.upper()}", disposable=True) # an experiment: removable in one call
# 4. The tutorial data: three tables written once; a second run keeps them.
try:
S = tdfs4ds.create_tutorial_data(S.name, DATABASE)
except ValueError:
S = dataclasses.replace(S, database=DATABASE)
def register_entity_features():
"""Page 1 in one call: (re)register the entity features and return the process id."""
sql = f"""
SELECT {S.entity}, COUNT(*) AS nb_events, SUM({S.amount}) AS total_amount,
AVG({S.amount}) AS avg_amount, COUNT(DISTINCT {S.partner}) AS nb_partners
FROM {S.table('events')}
GROUP BY 1"""
return tdfs4ds.upload_features(
df=None, sql_query=sql, target_view_name=f"{S.database}.{S.name}_entity_features",
entity_id=[S.entity], feature_names=["nb_events", "total_amount", "avg_amount", "nb_partners"],
replace=True, document=False, optimize_query=False, return_process_id=True)
You should see the connection and the data domain, as on every page.
The problem¶
In SQL, NULL = NULL is unknown, not true: an equi-join on a key never matches when either
side is NULL. The ingestion MERGE joins the incoming rows to the stored ones on the entity
columns, so a row with a NULL key could neither update nor insert. tdfs4ds does not
let it pass in silence: it refuses the batch and names the column.
1 · See the NULL keys¶
nulls = tdml.execute_sql(
f"SELECT COUNT(*) FROM {S.table('events')} WHERE {S.partner} IS NULL").fetchall()
print(nulls[0][0], "events without a", S.partner)
Output with scenario='retail': about 1% of the 50,000 events (the count is the same on every run).
2 · Without a substitute: refused¶
partner_sql = f"""
SELECT {S.partner}
, COUNT(*) AS partner_nb_events
, SUM({S.amount}) AS partner_total_amount
FROM {S.table('events')}
GROUP BY 1"""
try:
tdfs4ds.upload_features(
df=None, sql_query=partner_sql,
target_view_name=f"{S.database}.{S.name}_partner_features",
entity_id=[S.partner],
feature_names=["partner_nb_events", "partner_total_amount"],
replace=True, document=False, optimize_query=False, return_process_id=True,
)
except Exception as exc:
print(str(exc)[:200])
Output: the refusal, with the column name and the advice to pass entity_null_substitute (cut at 200 characters by the print). Nothing is stored.
Invalid process: NULL value(s) in entity/primary-index key column(s): MerchantID (1 NULL row(s)). NULL keys produce a cartesian-product MERGE. Filter the NULL rows upstream, or pass entity_null_substi
(The refusal may also appear only in the log, depending on where the check fires.)
3 · With a substitute¶
entity_null_substitute maps each entity column to a sentinel. The staging step applies
COALESCE(column, sentinel), so the keys are never NULL and the MERGE compares them with
plain equality:
process_id = tdfs4ds.upload_features(
df=None, sql_query=partner_sql,
target_view_name=f"{S.database}.{S.name}_partner_features",
entity_id=[S.partner],
feature_names=["partner_nb_events", "partner_total_amount"],
entity_null_substitute={S.partner: -1}, # a number for a numeric key, 'UNKNOWN' for text
replace=True, document=False, optimize_query=False, return_process_id=True,
)
print(process_id)
Output: a process id (<process id>) and a normal run. The events without a partner are stored
under the entity -1; a downstream query finds them there. Pass the same sentinel each
time the process is registered again, or the history splits.
dataset = tdfs4ds.build_dataset(
entity_id=[S.partner],
selected_features=["partner_nb_events", "partner_total_amount"],
view_name=f"{S.database}.{S.name}_partner_dataset",
)
print(dataset.shape)
Output with scenario='retail': 201 rows (the 200 merchants and the -1 bucket, whose
partner_nb_events is the 525 events without a merchant) and three columns.
Choosing a sentinel¶
It must be a value that cannot collide with a real key; if it can, legitimate rows merge with the NULL bucket, which is worse.
| Entity-ID type | Sentinel |
|---|---|
BIGINT / INTEGER |
-1 (or another reserved negative value) |
VARCHAR |
'UNKNOWN', '__NULL__' |
DATE |
DATE '1900-01-01' |
TIMESTAMP |
TIMESTAMP '1900-01-01 00:00:00' |
Composability¶
entity_null_substitute works with FilterManager and
TimeManager: the substitution is applied at staging time for every
iteration, so segmented and replayed ingestion behave the same.
Clean up¶
tdfs4ds.remove_process(process_id, drop_view=True, refresh_index=False) removes this process.
Module 13 lists everything.
Learn more¶
- upload_features: the parameter is part of the public signature.
- Data model: entity-ID semantics and the hidden-tables pattern.