6. FilterManager¶
Reference
The reference for this topic is FilterManager.
When the source is too large to ingest in one pass, or is partitioned and you want to
exploit that, a FilterManager steps through it one segment at a time. The process view
stays the same SQL; the current segment is read through a scalar subquery on the manager's
one-row view. Here the segments are the five regions of the tutorial entities.
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.
Why segmented ingestion¶
- Memory. One MERGE over a huge source spools for a long time and can fail before the run is recorded; smaller chunks succeed independently.
- Failure isolation. A failing segment logs
FAILED,...in the follow-up table and the loop continues; you re-run the bad one on its own (module 11). - Partition pruning. If the source is partitioned on the filter column, each iteration skips the other partitions (module 8).
The segments must split the entity. Each segment writes its own rows, so no two segments
may produce the same entity key: the segment column goes in the entity ([S.entity, "Region"]
below), or each entity falls in one segment (here each entity has one region).
1 · The segments¶
from tdfs4ds.utils.filter_management import FilterManager
fm = FilterManager(table_name=f"{S.name}_filter_region", schema_name=DATABASE)
fm.load_filter(tdml.DataFrame.from_query(f"SELECT DISTINCT Region FROM {S.table('entities')}"))
print(fm.nb_filters, "segments")
fm.update(filter_id=2)
print(fm.display())
fm.update(filter_id=1)
Output with scenario='retail': the number of segments and a one-row table with the region of segment 2 (the
cursor; the order of the regions is not fixed).
update moves the cursor by hand, to look at one segment; run moves it for you.
2 · A process that reads the current segment¶
The view reads the segment through a scalar subquery on the manager's view (never a join and never a hard-coded value):
sql = f"""
SELECT e.{S.entity}
, e.Region
, COUNT(*) AS nb_events_region
, SUM(t.{S.amount}) AS total_amount_region
FROM {S.table('events')} t
JOIN {S.table('entities')} e ON t.{S.entity} = e.{S.entity}
WHERE e.Region = (SELECT Region FROM {fm.sql_view})
GROUP BY e.{S.entity}, e.Region"""
process_id = tdfs4ds.upload_features(
df=None, sql_query=sql,
target_view_name=f"{S.database}.{S.name}_region_features",
entity_id=[S.entity, "Region"],
feature_names=["nb_events_region", "total_amount_region"],
filtermanager=fm, # attaches the manager: run() loops over its segments
replace=True, document=False, optimize_query=False,
run_now=False, return_process_id=True,
)
tdfs4ds.run(process_id, on_failure="raise")
You should see five ingestions in the log, one per region, then a normal end.
on_failure="raise" attempts every segment and raises once if any failed.
3 · One follow-up row per segment¶
follow_up = tdfs4ds.follow_up_report(process_id=process_id).to_pandas().reset_index()
print(follow_up[["APPLIED_FILTER", "STATUS", "START_DATETIME"]])
Output: five rows, one per region, all COMPLETED. A failed segment would
show FAILED,<error> on its own row while the others complete.
APPLIED_FILTER STATUS START_DATETIME
0 {"Region":"West"} COMPLETED 2026-...
1 {"Region":"South"} COMPLETED 2026-...
2 {"Region":"North"} COMPLETED 2026-...
3 {"Region":"East"} COMPLETED 2026-...
4 {"Region":"Central"} COMPLETED 2026-...
4 · Segment by segment equals all at once¶
dataset = tdfs4ds.build_dataset(
entity_id=[S.entity, "Region"],
selected_features=["nb_events_region", "total_amount_region"],
view_name=f"{S.database}.{S.name}_region_dataset",
)
by_region = tdml.DataFrame.from_query(
f"SELECT Region, COUNT(*) AS nb_entities FROM {S.database}.{S.name}_region_dataset GROUP BY 1")
print(by_region.to_pandas())
print(dataset.shape)
Output: five regions whose counts add up to the number of entities that have
events (here 1979), the same count as SELECT COUNT(DISTINCT ...) on the source.
The modes¶
| Mode | Segment | When |
|---|---|---|
| Standard | one value of a column | one slice at a time (this page) |
| With a TimeManager | the same segments at each business date | a history computed segment by segment (module 7) |
| Hybrid | a (value, date) pair (time_column=) |
a daily backfill per category |
| Clone | a copy of another manager's segments | another process needs the same segments with its own cursor |
fm_copy = FilterManager(table_name=f"{S.name}_filter_region_copy", schema_name=DATABASE)
fm_copy.clone_filter(fm, if_exists="replace")
print(fm_copy.nb_filters)
tdml.execute_sql(f"DROP VIEW {DATABASE}.{S.name}_filter_region_copy") # only a demonstration: remove the copy
Output: 5. The copy has its own cursor, moving it does not move fm.
Clean up¶
tdfs4ds.remove_process(process_id, drop_view=True, refresh_index=False) removes the process; the
manager tables <flavor>_filter_region* are dropped with DROP TABLE. Module 13 lists everything.
Learn more¶
- FilterManager: full mode reference, inspection methods, cloning, ownership and pruning.
- Recipes › Hybrid date × partition filter: date and a categorical column together.
- Module 8 › Partitioning: why FilterManager pairs naturally with partitioned sources.