Skip to content

Register your first feature

A feature is a number about an entity (a customer, an account, a machine...), computed by a SQL query and stored with its validity period. This page registers four of them from the tutorial data, in four steps.

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 a few log lines (feature store connected, data domain TUTORIAL_RETAIL created, the three tutorial tables written) and no error. Change "retail" to another flavor to run the page on other data (the eight flavors).

1 · Write the feature query

One row per entity, one column per feature. The entity key goes first, the features are the aggregates:

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"""
print(tdml.DataFrame.from_query(sql).head(3))

Output with scenario='retail' (three rows, in any order): the entity id and the four features.

   CustomerID  nb_events  total_amount  avg_amount  nb_partners
0      101027         22       2987.64  135.801818           20
1      100412         17       4741.86  278.932941           15
2      100388          8        763.02   95.377500            8

2 · Register and ingest with upload_features

upload_features creates the process view from the SQL, records it in the process catalog, registers the features, runs the process once and stores the values.

process_id = tdfs4ds.upload_features(
    df=None,                                          # the source is the SQL above
    sql_query=sql,
    target_view_name=f"{S.database}.{S.name}_entity_features",
    entity_id=[S.entity],                             # a LIST of column names
    feature_names=["nb_events", "total_amount", "avg_amount", "nb_partners"],
    replace=True,                                     # so this page can be run twice
    document=False, optimize_query=False,             # the AI steps are modules 2 and 3
    return_process_id=True,
)
print(process_id)

Output: a process id (a UUID).

<process id>

It is the handle of this process: the view stays in the database, so run(process_id) re-computes it later without this Python.

entity_id is a list of column names

Pass the key column(s) as a list, e.g. [S.entity] or ['CUSTOMER_ID', 'EVENT_DATE']. The SQL types are read from the source, with their exact length and character set.

3 · Confirm the registration

features = tdfs4ds.feature_catalog(as_pandas=True)
print(features[["DATA_DOMAIN", "ENTITY_NAME", "FEATURE_NAME", "FEATURE_TABLE"]])

processes = tdfs4ds.process_catalog(as_pandas=True)
print(processes[["PROCESS_ID", "VIEW_NAME"]])

Output with scenario='retail': four features in the domain TUTORIAL_RETAIL under the entity column (stored in FS_T_... tables), and one process whose view ends with _entity_features.

       DATA_DOMAIN  ...                              FEATURE_TABLE
0  TUTORIAL_RETAIL  ...  FS_T_e1e9e153_5687_536a_a9ad_fd8de414dcff
1  TUTORIAL_RETAIL  ...  FS_T_fb7e8998_e6c7_55fb_8f4c_4440540f8a86
2  TUTORIAL_RETAIL  ...  FS_T_fb7e8998_e6c7_55fb_8f4c_4440540f8a86
3  TUTORIAL_RETAIL  ...  FS_T_e1e9e153_5687_536a_a9ad_fd8de414dcff

[4 rows x 4 columns]
                             PROCESS_ID                             VIEW_NAME
0  <process id>  " if(# Register your first feature

A *feature* is a number about an entity (a customer, an account, a machine...), computed
by a SQL query and stored with its validity period. This page registers four of them from
the tutorial data, in four steps.

```python
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 a few log lines (feature store connected, data domain TUTORIAL_RETAIL created, the three tutorial tables written) and no error. Change "retail" to another flavor to run the page on other data (the eight flavors).

1 · Write the feature query

One row per entity, one column per feature. The entity key goes first, the features are the aggregates:

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"""
print(tdml.DataFrame.from_query(sql).head(3))

Output with scenario='retail' (three rows, in any order): the entity id and the four features.

   CustomerID  nb_events  total_amount  avg_amount  nb_partners
0      101027         22       2987.64  135.801818           20
1      100412         17       4741.86  278.932941           15
2      100388          8        763.02   95.377500            8

2 · Register and ingest with upload_features

upload_features creates the process view from the SQL, records it in the process catalog, registers the features, runs the process once and stores the values.

process_id = tdfs4ds.upload_features(
    df=None,                                          # the source is the SQL above
    sql_query=sql,
    target_view_name=f"{S.database}.{S.name}_entity_features",
    entity_id=[S.entity],                             # a LIST of column names
    feature_names=["nb_events", "total_amount", "avg_amount", "nb_partners"],
    replace=True,                                     # so this page can be run twice
    document=False, optimize_query=False,             # the AI steps are modules 2 and 3
    return_process_id=True,
)
print(process_id)

Output: a process id (a UUID).

<process id>

It is the handle of this process: the view stays in the database, so run(process_id) re-computes it later without this Python.

entity_id is a list of column names

Pass the key column(s) as a list, e.g. [S.entity] or ['CUSTOMER_ID', 'EVENT_DATE']. The SQL types are read from the source, with their exact length and character set.

3 · Confirm the registration

features = tdfs4ds.feature_catalog(as_pandas=True)
print(features[["DATA_DOMAIN", "ENTITY_NAME", "FEATURE_NAME", "FEATURE_TABLE"]])

processes = tdfs4ds.process_catalog(as_pandas=True)
print(processes[["PROCESS_ID", "VIEW_NAME"]])

Output with scenario='retail': four features in the domain TUTORIAL_RETAIL under the entity column (stored in FS_T_... tables), and one process whose view ends with _entity_features.

       DATA_DOMAIN  ...                              FEATURE_TABLE
0  TUTORIAL_RETAIL  ...  FS_T_e1e9e153_5687_536a_a9ad_fd8de414dcff
1  TUTORIAL_RETAIL  ...  FS_T_fb7e8998_e6c7_55fb_8f4c_4440540f8a86
2  TUTORIAL_RETAIL  ...  FS_T_fb7e8998_e6c7_55fb_8f4c_4440540f8a86
3  TUTORIAL_RETAIL  ...  FS_T_e1e9e153_5687_536a_a9ad_fd8de414dcff

[4 rows x 4 columns]
                             PROCESS_ID                             VIEW_NAME
0  <process id>  "demo_user"."retail_entity_features"

The FS_T_... names are derived from the entity and value type: the same on every run for this data.

4 · Re-run it later

tdfs4ds.run(process_id=process_id, force_compute=True)

You should see a log line for the run; a value that did not change is not stored again (its validity period just continues). Without force_compute=True, a process already completed for the current date is skipped.

Clean up

To remove what this page created: tdfs4ds.remove_process(process_id, drop_view=True, refresh_index=False) and tdfs4ds.drop_tutorial_data(S.name, DATABASE). The next pages reuse them, so keep them until the last tutorial page.

What's next

  • Build a dataset combining several features: First dataset.
  • Scale to large sources with FilterManager: Tutorial 6.
  • Backfill historical periods with TimeManager and roll_out: Tutorial 7.
  • Give the data domain one clock so its processes compute at the same business date: Managing time with the domain clock.
  • Document the process with an LLM: AI / Process documentation. .Value -ceq 'DEMO_USER'){'MY_DATABASE'}else{'my_database'} "."retail_entity_features"
    The `FS_T_...` names are derived from the entity and value type: the same on every run for this data.
    
    ## 4 · Re-run it later
    
    ```python
    tdfs4ds.run(process_id=process_id, force_compute=True)
    

You should see a log line for the run; a value that did not change is not stored again (its validity period just continues). Without force_compute=True, a process already completed for the current date is skipped.

Clean up

To remove what this page created: tdfs4ds.remove_process(process_id, drop_view=True, refresh_index=False) and tdfs4ds.drop_tutorial_data(S.name, DATABASE). The next pages reuse them, so keep them until the last tutorial page.

What's next