3030)
3131from feast .feature_view import DUMMY_ENTITY_ID , DUMMY_ENTITY_VAL , FeatureView
3232from feast .infra .offline_stores import offline_utils
33- from feast .infra .offline_stores .offline_store import OfflineStore , RetrievalJob
33+ from feast .infra .offline_stores .offline_store import (
34+ OfflineStore ,
35+ RetrievalJob ,
36+ RetrievalMetadata ,
37+ )
3438from feast .on_demand_feature_view import OnDemandFeatureView
3539from feast .registry import Registry
3640from feast .repo_config import FeastConfigBaseModel , RepoConfig
4347 from google .api_core .exceptions import NotFound
4448 from google .auth .exceptions import DefaultCredentialsError
4549 from google .cloud import bigquery
46- from google .cloud .bigquery import Client
50+ from google .cloud .bigquery import Client , Table
4751
4852except ImportError as e :
4953 from feast .errors import FeastExtrasDependencyImportError
@@ -148,16 +152,22 @@ def get_historical_features(
148152 config .offline_store .location ,
149153 )
150154
155+ entity_schema = _get_entity_schema (client = client , entity_df = entity_df ,)
156+
157+ entity_df_event_timestamp_col = offline_utils .infer_event_timestamp_from_entity_df (
158+ entity_schema
159+ )
160+
161+ entity_df_event_timestamp_range = _get_entity_df_event_timestamp_range (
162+ entity_df , entity_df_event_timestamp_col , client ,
163+ )
164+
151165 @contextlib .contextmanager
152166 def query_generator () -> Iterator [str ]:
153- entity_schema = _upload_entity_df_and_get_entity_schema (
167+ _upload_entity_df (
154168 client = client , table_name = table_reference , entity_df = entity_df ,
155169 )
156170
157- entity_df_event_timestamp_col = offline_utils .infer_event_timestamp_from_entity_df (
158- entity_schema
159- )
160-
161171 expected_join_keys = offline_utils .get_expected_join_keys (
162172 project , feature_views , registry
163173 )
@@ -166,10 +176,6 @@ def query_generator() -> Iterator[str]:
166176 entity_schema , expected_join_keys , entity_df_event_timestamp_col
167177 )
168178
169- entity_df_event_timestamp_range = _get_entity_df_event_timestamp_range (
170- entity_df , entity_df_event_timestamp_col , client , table_reference ,
171- )
172-
173179 # Build a query context containing all information required to template the BigQuery SQL query
174180 query_context = offline_utils .get_feature_view_query_context (
175181 feature_refs ,
@@ -204,6 +210,10 @@ def query_generator() -> Iterator[str]:
204210 on_demand_feature_views = OnDemandFeatureView .get_requested_odfvs (
205211 feature_refs , project , registry
206212 ),
213+ metadata = RetrievalMetadata (
214+ min_event_timestamp = entity_df_event_timestamp_range [0 ],
215+ max_event_timestamp = entity_df_event_timestamp_range [1 ],
216+ ),
207217 )
208218
209219
@@ -215,6 +225,7 @@ def __init__(
215225 config : RepoConfig ,
216226 full_feature_names : bool ,
217227 on_demand_feature_views : Optional [List [OnDemandFeatureView ]] = None ,
228+ metadata : Optional [RetrievalMetadata ] = None ,
218229 ):
219230 if not isinstance (query , str ):
220231 self ._query_generator = query
@@ -232,6 +243,7 @@ def query_generator() -> Iterator[str]:
232243 self ._on_demand_feature_views = (
233244 on_demand_feature_views if on_demand_feature_views else []
234245 )
246+ self ._metadata = metadata
235247
236248 @property
237249 def full_feature_names (self ) -> bool :
@@ -323,8 +335,13 @@ def persist(self, storage: SavedDatasetStorage) -> "BigQueryRetrievalJob":
323335 client = self .client ,
324336 config = self .config ,
325337 full_feature_names = self .full_feature_names ,
338+ metadata = self .metadata ,
326339 )
327340
341+ @property
342+ def metadata (self ) -> Optional [RetrievalMetadata ]:
343+ return self ._metadata
344+
328345
329346def block_until_done (
330347 client : Client ,
@@ -395,46 +412,57 @@ def _get_table_reference_for_new_entity(
395412 return f"{ dataset_project } .{ dataset_name } .{ table_name } "
396413
397414
398- def _upload_entity_df_and_get_entity_schema (
415+ def _upload_entity_df (
399416 client : Client , table_name : str , entity_df : Union [pd .DataFrame , str ],
400- ) -> Dict [ str , np . dtype ] :
417+ ) -> Table :
401418 """Uploads a Pandas entity dataframe into a BigQuery table and returns the resulting table"""
402419
403420 if isinstance (entity_df , str ):
404421 job = client .query (f"CREATE TABLE { table_name } AS ({ entity_df } )" )
405- block_until_done (client , job )
406422
407- limited_entity_df = (
408- client .query (f"SELECT * FROM { table_name } LIMIT 1" ).result ().to_dataframe ()
409- )
410-
411- entity_schema = dict (zip (limited_entity_df .columns , limited_entity_df .dtypes ))
412423 elif isinstance (entity_df , pd .DataFrame ):
413- # Drop the index so that we dont have unnecessary columns
424+ # Drop the index so that we don't have unnecessary columns
414425 entity_df .reset_index (drop = True , inplace = True )
415426 job = client .load_table_from_dataframe (entity_df , table_name )
416- block_until_done (client , job )
417- entity_schema = dict (zip (entity_df .columns , entity_df .dtypes ))
418427 else :
419428 raise InvalidEntityType (type (entity_df ))
420429
430+ block_until_done (client , job )
431+
421432 # Ensure that the table expires after some time
422433 table = client .get_table (table = table_name )
423434 table .expires = datetime .utcnow () + timedelta (minutes = 30 )
424435 client .update_table (table , ["expires" ])
425436
437+ return table
438+
439+
440+ def _get_entity_schema (
441+ client : Client , entity_df : Union [pd .DataFrame , str ]
442+ ) -> Dict [str , np .dtype ]:
443+ if isinstance (entity_df , str ):
444+ entity_df_sample = (
445+ client .query (f"SELECT * FROM ({ entity_df } ) LIMIT 1" ).result ().to_dataframe ()
446+ )
447+
448+ entity_schema = dict (zip (entity_df_sample .columns , entity_df_sample .dtypes ))
449+ elif isinstance (entity_df , pd .DataFrame ):
450+ entity_schema = dict (zip (entity_df .columns , entity_df .dtypes ))
451+ else :
452+ raise InvalidEntityType (type (entity_df ))
453+
426454 return entity_schema
427455
428456
429457def _get_entity_df_event_timestamp_range (
430458 entity_df : Union [pd .DataFrame , str ],
431459 entity_df_event_timestamp_col : str ,
432460 client : Client ,
433- table_name : str ,
434461) -> Tuple [datetime , datetime ]:
435462 if type (entity_df ) is str :
436463 job = client .query (
437- f"SELECT MIN({ entity_df_event_timestamp_col } ) AS min, MAX({ entity_df_event_timestamp_col } ) AS max FROM { table_name } "
464+ f"SELECT MIN({ entity_df_event_timestamp_col } ) AS min, MAX({ entity_df_event_timestamp_col } ) AS max "
465+ f"FROM ({ entity_df } )"
438466 )
439467 res = next (job .result ())
440468 entity_df_event_timestamp_range = (
0 commit comments