3. Query optimization¶
Reference
The reference for this topic is Query optimizer.
Needs an instruct model
The optimizer asks a language model for rewrites. Set INSTRUCT_MODEL_PROVIDER,
INSTRUCT_MODEL_MODEL and INSTRUCT_MODEL_API_KEY (plus INSTRUCT_MODEL_URL or
INSTRUCT_MODEL_REGION for your provider), and check them with
tdfs4ds.check_configuration(). Without a model the call below returns an error
result and changes nothing.
Goal: score the plan of the process view from module 1 and let the optimizer propose a faster, equivalent SQL. Your SQL is never rewritten silently: every candidate is checked against the original (it must compile, keep the same joins, filters and grain) before it can replace it.
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)
process_id = register_entity_features()
You should see a process id.
1 · Optimize the registered process¶
result = tdfs4ds.skill_optimize_query(process_id=process_id)
print(result["status"], result["score_delta"])
print(result["answer"])
You should see ok and the change of EXPLAIN score, then the summary of the report
(original_sql, best_sql, the analysis of each candidate are in the same dictionary). The query of module 1 is already simple, so the
usual verdict is no better rewrite found: the original is kept. The full Markdown report
is written under QUERY_OPTIMIZER_REPORT_DIR.
2 · Optimize a query that is not registered¶
Give the SQL text instead of a process id: nothing is stored and nothing is replaced.
slow_sql = f"""
SELECT e.{S.entity},
(SELECT COUNT(*) FROM {S.table('events')} x WHERE x.{S.entity} = e.{S.entity}) AS nb_events,
(SELECT SUM(x.{S.amount}) FROM {S.table('events')} x WHERE x.{S.entity} = e.{S.entity}) AS total_amount
FROM {S.table('entities')} e"""
result = tdfs4ds.skill_optimize_query(sql_query=slow_sql)
print(result.get("best_sql") or "no rewrite")
You should see the SQL of the best candidate: the two correlated sub-queries become
one LEFT JOIN on a pre-aggregation (one scan of the events table instead of two per
entity), with the same columns.
3 · Optimize at registration time¶
upload_features(optimize_query=True, update_view=True) runs the same optimizer before the
first run and replaces the view by the best candidate when it is better and equivalent;
max_candidates= limits the number of rewrites tried for the call.
process_id = tdfs4ds.upload_features(
df=None, sql_query=slow_sql,
target_view_name=f"{S.database}.{S.name}_slow_features",
entity_id=[S.entity], feature_names=["nb_events", "total_amount"],
replace=True, optimize_query=True, update_view=True, max_candidates=2,
document=False, return_process_id=True,
)
print(process_id)
You should see the optimizer's log, then the process registered on the optimized view.
Clean up¶
The extra process <flavor>_slow_features is only for this page:
tdfs4ds.remove_process(process_id, refresh_index=False) removes it. Module 13 lists the rest.
Learn more¶
- Query optimizer: the full pipeline.
- EXPLAIN scoring: what each signal means.
- Recipes › Upload & document: combine optimize and document in one call.