8. Partitioning¶
Reference
The reference for this topic is FilterManager.
A feature table that grows by millions of rows a day becomes the slowest part of every query
that touches it. Teradata's answer is partitioning: split the rows physically on a
column so that a predicate on it reads only a fraction of the table. upload_features
exposes both controls: primary_index and partitioning.
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)
from tdfs4ds.utils.show_text import show_text
You should see the connection and the data domain, as on every page.
Two kinds of "index"¶
- PRIMARY INDEX governs row distribution across AMPs. A good one spreads rows
evenly; a
WHEREon it routes the query to one AMP but does not skip data. - PARTITION BY governs the scan footprint within an AMP: a
WHEREon the partition column skips whole partitions (partition elimination).
The usual pattern: the primary index is the entity key (even spread, fast lookup of one entity's history), the partitioning is a date or a bucket.
1 · The source is already partitioned¶
The tutorial events table has its primary index on the entity and one partition per day. Ask the optimizer what it does for one day:
plan = show_text(tdml.execute_sql(
f"EXPLAIN SELECT COUNT(*) FROM {S.table('events')} "
f"WHERE {S.event_date} = DATE '2023-06-15'").fetchall())
print([line for line in plan.splitlines() if "partition" in line.lower()])
Output with scenario='retail' (a one-element list holding the plan text, shortened here): the table is read from a single partition
instead of by an all-rows scan.
[' 1) First, we lock my_database.retail_transactions in TD_MAP1 for read on a reserved RowHash in a single partition ... 2) Next, we lock my_database.retail_transactions in TD_MAP1 for read on a single partition. 3) We do an all-AMPs SUM step ... to aggregate from a single partition of my_database.retail_transactions with a condition of ("my_database.retail_transactions.Date_transaction = DATE '2023-06-15'") ...']
This is what a FilterManager or a TimeManager filter on the date exploits (modules 6 and 7).
2 · Declare them on a feature table¶
Both controls are arguments to upload_features. primary_index is a list of entity
columns; partitioning is a raw Teradata clause, so RANGE_N or CASE_N need no special
support. The partition column must be an entity column: here a bucket of the entity key, in
four buckets.
sql = f"""
SELECT {S.entity}
, MOD(HASHBUCKET(HASHROW({S.entity})), 4) AS ENTITY_BUCKET
, COUNT(*) AS nb_events_bucketed
, SUM({S.amount}) AS total_amount_bucketed
FROM {S.table('events')}
GROUP BY 1, 2"""
process_id = tdfs4ds.upload_features(
df=None, sql_query=sql,
target_view_name=f"{S.database}.{S.name}_bucketed_features",
entity_id=[S.entity, "ENTITY_BUCKET"],
feature_names=["nb_events_bucketed", "total_amount_bucketed"],
primary_index=[S.entity],
partitioning="PARTITION BY RANGE_N(ENTITY_BUCKET BETWEEN 0 AND 3 EACH 1)",
replace=True, document=False, optimize_query=False, return_process_id=True,
)
print(process_id)
Output: a process id. The definition is checked before anything is
registered: upload_features tries the columns, primary index and partitioning on a
throwaway volatile table, and if the database refuses it nothing is registered and the log
gives the database message and what to change:
| Partitioning | Refusal | Fix |
|---|---|---|
RANGE_N on a DECIMAL / NUMBER / FLOAT column |
Error 3732 | cast it in the view (CAST(col AS INTEGER)), or use CASE_N |
RANGE_N on a TIMESTAMP column with DATE bounds |
Error 5714 | TIMESTAMP '2023-01-01 00:00:00' bounds, or a DATE column |
| a column that is not an entity column | Error 3810 | partition and index on entity columns only |
3 · Read the storage table¶
catalog = tdfs4ds.feature_catalog(as_pandas=True)
row = catalog[catalog["FEATURE_NAME"] == "nb_events_bucketed"].iloc[0]
print(show_text(tdml.execute_sql(f"SHOW TABLE {row['FEATURE_DATABASE']}.{row['FEATURE_TABLE']}").fetchall()))
Output (shortened): the CREATE MULTISET TABLE of the feature table, with the entity as
PRIMARY INDEX, a PARTITION BY on FEATURE_ID and, as a second level, a RANGE_N on the bucket:
CREATE MULTISET TABLE my_database.FS_T_... ,FALLBACK ,
...
(
CustomerID BIGINT,
ENTITY_BUCKET INTEGER,
FEATURE_ID BIGINT,
FEATURE_VALUE INTEGER,
FEATURE_VERSION VARCHAR(255) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
ValidStart TIMESTAMP(0) WITH TIME ZONE NOT NULL,
ValidEnd TIMESTAMP(0) WITH TIME ZONE NOT NULL,
PERIOD FOR ValidPeriod (ValidStart, ValidEnd) AS VALIDTIME)
PRIMARY INDEX ( CustomerID )
PARTITION BY ( RANGE_N(FEATURE_ID BETWEEN 0 AND 20000 EACH 1 ),
RANGE_N(ENTITY_BUCKET BETWEEN 0 AND 3 EACH 1 ) );
The definition is recorded with the process: registering the same view
again with another primary_index or partitioning keeps the recorded one and logs a
warning. Change it with plan_relocation(process_id=..., primary_index=..., partitioning=...), which
moves the stored history.
4 · What the dependency graph says¶
The lineage graph reports the primary index and partition columns of every table it walks, which tells you which columns Teradata can eliminate on:
from tdfs4ds.lineage import build_teradata_dependency_graph
entity_process = register_entity_features()
sql_text = tdfs4ds.get_process_info(entity_process)["PROCESS_SQL"]
graph = build_teradata_dependency_graph(sql_query=sql_text)
for name, node in graph["nodes"].items():
info = node.get("table_info") or {}
print(name, "PI:", info.get("primary_index_columns"), "partitions:", info.get("partition_columns"))
Output with scenario='retail': the events table with the entity as primary index and the event date as
its partition column, next to the view (a view has neither).
"my_database"."retail_entity_features" PI: None partitions: None
"my_database"."retail_transactions" PI: ['CustomerID'] partitions: ['Date_transaction']
Clean up¶
tdfs4ds.remove_process(process_id, drop_view=True, refresh_index=False) removes the bucketed process (its
storage table stays: it holds the stored values; remove_feature and purge options are in
Maintain a workflow). Module 13 lists everything.
Learn more¶
- Dependency graph:
primary_index_columns,partition_columns,partitioning_levelson every node. - upload_features: full parameter list.
- FilterManager: the natural partner.
- Query optimizer: flags partitioned-but-unfiltered access paths and proposes rewrites.