Skip to content

Commit 6b8ee61

Browse files
NopeCharonntkathole
authored andcommitted
feat: Retrieve historical features from Trino without an entity dataframe
TrinoOfflineStore.get_historical_features did not accept start_date or end_date, so calling FeatureStore.get_historical_features without an entity_df failed with "unexpected keyword argument 'start_date'" on Trino. When entity_df is None, build the left side of the point-in-time join from the data itself: a UNION of the distinct join keys that each feature view source has between start_date and end_date, with every row stamped at end_date. Each entity then gets its latest feature values within the TTL, matching the BigQuery and Spark offline stores. The entity subquery is inlined into the existing point-in-time template, so no temporary table is created and read-only catalogs work. It selects through the query context's entity selections and timestamp field, so field mappings and join key projections are honoured. Join keys a feature view does not have are filled with NULL, feature views without entities join on the timestamp only, and when no feature view has entities the left side is a single row at end_date. start_date and end_date default through compute_non_entity_date_range like the other stores. Document entity-less retrieval for Trino in the offline store reference, the feature retrieval concepts page and the FAQ. Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com>
1 parent cc17aad commit 6b8ee61

5 files changed

Lines changed: 488 additions & 3 deletions

File tree

‎docs/getting-started/concepts/feature-retrieval.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ training_df = store.get_historical_features(
175175
If `start_date` is omitted, it defaults to `end_date` minus the feature view TTL. If `end_date` is omitted, it defaults to the current time. Point-in-time correctness is still preserved.
176176

177177
{% hint style="warning" %}
178-
Entity-less retrieval is currently supported for the **Postgres**, **Dask**, **Spark**, and **Ray** offline stores. You cannot mix `entity_df` with `start_date`/`end_date` in the same call.
178+
Entity-less retrieval is currently supported for the **Postgres**, **Dask**, **Spark**, **Ray**, and **Trino** offline stores. You cannot mix `entity_df` with `start_date`/`end_date` in the same call.
179179
{% endhint %}
180180

181181
For more details, see the [FAQ](../faq.md#how-do-i-run-get_historical_features-without-providing-an-entity-dataframe) and [this blog post on entity-less historical feature retrieval](https://feast.dev/blog/entity-less-historical-features-retrieval/).

‎docs/getting-started/faq.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ Yes, this is possible. For example, you can use BigQuery as an offline store and
4141

4242
Feast does support fetching historical features without passing an entity dataframe with the request.
4343

44-
- **Supported offline stores:** Entity-less (entity dataframe–less) retrieval is supported for the **Postgres**, **Dask**, **Spark**, and **Ray** offline stores. Postgres was the first to support it; Dask, Spark, and Ray have followed. Other offline stores may be added based on priority and community demand.
44+
- **Supported offline stores:** Entity-less (entity dataframe–less) retrieval is supported for the **Postgres**, **Dask**, **Spark**, **Ray**, and **Trino** offline stores. Postgres was the first to support it; Dask, Spark, Ray, and Trino have followed. Other offline stores may be added based on priority and community demand.
4545
- **Date range:** Retrieval is controlled by the `start_date` and `end_date` parameters. Supported combinations:
4646
- Both params given → data in the given start-to-end time range.
4747
- Only `start_date` given → data from the start date to now.

‎docs/reference/offline-stores/trino.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
The Trino offline store provides support for reading [TrinoSources](../data-sources/trino.md).
66
* Entity dataframes can be provided as a SQL query or can be provided as a Pandas dataframe. A Pandas dataframes will be uploaded to Trino as a table in order to complete join operations.
7+
* Historical features can also be retrieved without an entity dataframe by passing `start_date` and/or `end_date` to `get_historical_features`. Every entity key with an event between `start_date` and `end_date` is joined as of `end_date`, so each entity gets its latest feature values within the feature view TTL. No temporary table is created in this mode. See [entity-less retrieval](../../getting-started/concepts/feature-retrieval.md) for details.
78

89
## Disclaimer
910

‎sdk/python/feast/infra/offline_stores/contrib/trino_offline_store/trino.py‎

Lines changed: 140 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
from feast.on_demand_feature_view import OnDemandFeatureView
6060
from feast.repo_config import FeastConfigBaseModel, RepoConfig
6161
from feast.saved_dataset import SavedDatasetStorage
62+
from feast.utils import compute_non_entity_date_range
6263

6364
logger = logging.getLogger(__name__)
6465

@@ -372,18 +373,33 @@ def get_historical_features(
372373
config: RepoConfig,
373374
feature_views: List[FeatureView],
374375
feature_refs: List[str],
375-
entity_df: Union[pd.DataFrame, str],
376+
entity_df: Optional[Union[pd.DataFrame, str]],
376377
registry: BaseRegistry,
377378
project: str,
378379
full_feature_names: bool = False,
379380
filter_by_created_timestamp: bool = False,
381+
**kwargs: Any,
380382
) -> TrinoRetrievalJob:
381383
assert isinstance(config.offline_store, TrinoOfflineStoreConfig)
382384
for fv in feature_views:
383385
assert isinstance(fv.batch_source, TrinoSource)
384386

385387
client = _get_trino_client(config=config)
386388

389+
if entity_df is None:
390+
return _get_historical_features_without_entity_df(
391+
config=config,
392+
client=client,
393+
feature_views=feature_views,
394+
feature_refs=feature_refs,
395+
registry=registry,
396+
project=project,
397+
full_feature_names=full_feature_names,
398+
filter_by_created_timestamp=filter_by_created_timestamp,
399+
start_date=kwargs.get("start_date"),
400+
end_date=kwargs.get("end_date"),
401+
)
402+
387403
table_reference = _get_table_reference_for_new_entity(
388404
catalog=config.offline_store.catalog,
389405
dataset_name=config.offline_store.dataset,
@@ -1302,6 +1318,129 @@ def _upload_entity_df_and_get_entity_schema(
13021318
raise InvalidEntityType(type(entity_df))
13031319

13041320

1321+
def _get_historical_features_without_entity_df(
1322+
config: RepoConfig,
1323+
client: Trino,
1324+
feature_views: List[FeatureView],
1325+
feature_refs: List[str],
1326+
registry: BaseRegistry,
1327+
project: str,
1328+
full_feature_names: bool,
1329+
filter_by_created_timestamp: bool,
1330+
start_date: Optional[datetime],
1331+
end_date: Optional[datetime],
1332+
) -> TrinoRetrievalJob:
1333+
"""
1334+
Retrieves historical features for a time range instead of an entity dataframe.
1335+
1336+
The left side of the point-in-time join is built from the entity keys observed
1337+
in the feature view sources between start_date and end_date, each joined as of
1338+
end_date, so every entity gets its latest feature values within the TTL.
1339+
"""
1340+
start_date, end_date = compute_non_entity_date_range(
1341+
feature_views,
1342+
start_date=start_date,
1343+
end_date=end_date,
1344+
)
1345+
1346+
query_context = offline_utils.get_feature_view_query_context(
1347+
feature_refs=feature_refs,
1348+
feature_views=feature_views,
1349+
registry=registry,
1350+
project=project,
1351+
entity_df_timestamp_range=(start_date, end_date),
1352+
)
1353+
1354+
entity_df_event_timestamp_col = offline_utils.DEFAULT_ENTITY_DF_EVENT_TIMESTAMP_COL
1355+
join_keys = offline_utils.gather_all_entities(query_context)
1356+
entity_df_columns = {
1357+
column: None for column in join_keys + [entity_df_event_timestamp_col]
1358+
}.keys()
1359+
1360+
query = offline_utils.build_point_in_time_query(
1361+
query_context,
1362+
left_table_query_string=_build_non_entity_left_table_query(
1363+
query_context=query_context,
1364+
join_keys=join_keys,
1365+
start_date=start_date,
1366+
end_date=end_date,
1367+
entity_df_event_timestamp_col=entity_df_event_timestamp_col,
1368+
),
1369+
entity_df_event_timestamp_col=entity_df_event_timestamp_col,
1370+
entity_df_columns=entity_df_columns,
1371+
query_template=MULTIPLE_FEATURE_VIEW_POINT_IN_TIME_JOIN,
1372+
full_feature_names=full_feature_names,
1373+
filter_by_created_timestamp=filter_by_created_timestamp,
1374+
)
1375+
1376+
return TrinoRetrievalJob(
1377+
query=query,
1378+
client=client,
1379+
config=config,
1380+
full_feature_names=full_feature_names,
1381+
on_demand_feature_views=OnDemandFeatureView.get_requested_odfvs(
1382+
feature_refs, project, registry
1383+
),
1384+
metadata=RetrievalMetadata(
1385+
features=feature_refs,
1386+
keys=join_keys,
1387+
min_event_timestamp=start_date,
1388+
max_event_timestamp=end_date,
1389+
),
1390+
)
1391+
1392+
1393+
def _build_non_entity_left_table_query(
1394+
query_context: List[offline_utils.FeatureViewQueryContext],
1395+
join_keys: List[str],
1396+
start_date: datetime,
1397+
end_date: datetime,
1398+
entity_df_event_timestamp_col: str,
1399+
) -> str:
1400+
"""
1401+
Builds a subquery that stands in for the entity dataframe in non-entity mode.
1402+
1403+
It selects the distinct join keys of every feature view with entities whose
1404+
source has events between start_date and end_date, fills the join keys a
1405+
feature view does not have with NULL, and sets the event timestamp of every
1406+
row to end_date. Feature views without entities join on the timestamp alone,
1407+
so they do not contribute rows. When no feature view has entities, the
1408+
subquery is a single row holding end_date.
1409+
"""
1410+
start_timestamp = _to_trino_timestamp_literal(start_date)
1411+
end_timestamp = _to_trino_timestamp_literal(end_date)
1412+
1413+
entity_selects = []
1414+
for context in query_context:
1415+
if not context.entities:
1416+
continue
1417+
selections = dict(zip(context.entities, context.entity_selections))
1418+
columns = ", ".join(
1419+
selections.get(join_key, f"NULL AS {join_key}") for join_key in join_keys
1420+
)
1421+
entity_selects.append(
1422+
f"SELECT DISTINCT {columns} "
1423+
f"FROM ({context.table_subquery}) "
1424+
f"WHERE {context.timestamp_field} "
1425+
f"BETWEEN {start_timestamp} AND {end_timestamp}"
1426+
)
1427+
1428+
if not entity_selects:
1429+
return f"(SELECT {end_timestamp} AS {entity_df_event_timestamp_col})"
1430+
1431+
entity_union = "\n UNION\n ".join(entity_selects)
1432+
return f"""(
1433+
SELECT *, {end_timestamp} AS {entity_df_event_timestamp_col}
1434+
FROM (
1435+
{entity_union}
1436+
)
1437+
)"""
1438+
1439+
1440+
def _to_trino_timestamp_literal(timestamp: datetime) -> str:
1441+
return f"from_iso8601_timestamp('{timestamp.astimezone(timezone.utc).isoformat()}')"
1442+
1443+
13051444
def _get_trino_client(config: RepoConfig) -> Trino:
13061445
auth = None
13071446
if config.offline_store.auth is not None:

0 commit comments

Comments
 (0)