-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathfeature_view.py
3944 lines (3501 loc) · 175 KB
/
feature_view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2022 Logical Clocks AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import json
import logging
import warnings
from datetime import date, datetime
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, TypeVar, Union
import humps
import numpy as np
import pandas as pd
import polars as pl
from hsfs import (
feature_group,
storage_connector,
tag,
training_dataset,
training_dataset_feature,
usage,
util,
)
from hsfs import serving_key as skm
from hsfs.client.exceptions import FeatureStoreException
from hsfs.constructor import filter, query
from hsfs.constructor.filter import Filter, Logic
from hsfs.core import (
explicit_provenance,
feature_monitoring_config_engine,
feature_monitoring_result_engine,
feature_view_engine,
job,
statistics_engine,
transformation_function_engine,
vector_server,
)
from hsfs.core import feature_monitoring_config as fmc
from hsfs.core import feature_monitoring_result as fmr
from hsfs.core.feature_view_api import FeatureViewApi
from hsfs.core.vector_db_client import VectorDbClient
from hsfs.decorators import typechecked
from hsfs.feature import Feature
from hsfs.hopsworks_udf import HopsworksUdf
from hsfs.statistics import Statistics
from hsfs.statistics_config import StatisticsConfig
from hsfs.training_dataset_split import TrainingDatasetSplit
from hsfs.transformation_function import TransformationFunction
_logger = logging.getLogger(__name__)
TrainingDatasetDataFrameTypes = Union[
pd.DataFrame,
TypeVar("pyspark.sql.DataFrame"), # noqa: F821
TypeVar("pyspark.RDD"), # noqa: F821
np.ndarray,
List[List[Any]],
pl.DataFrame,
]
SplineDataFrameTypes = Union[
pd.DataFrame,
TypeVar("pyspark.sql.DataFrame"), # noqa: F821
TypeVar("pyspark.RDD"), # noqa: F821
np.ndarray,
List[List[Any]],
TypeVar("SplineGroup"), # noqa: F821
]
@typechecked
class FeatureView:
ENTITY_TYPE = "featureview"
def __init__(
self,
name: str,
query: query.Query,
featurestore_id: int,
id: Optional[int] = None,
version: Optional[int] = None,
description: Optional[str] = "",
labels: Optional[List[str]] = None,
inference_helper_columns: Optional[List[str]] = None,
training_helper_columns: Optional[List[str]] = None,
transformation_functions: Optional[
List[Union[TransformationFunction, HopsworksUdf]]
] = None,
featurestore_name: Optional[str] = None,
serving_keys: Optional[List[skm.ServingKey]] = None,
logging_enabled: Optional[bool] = False,
**kwargs,
) -> None:
self._name = name
self._id = id
self._query = query
self._featurestore_id = featurestore_id
self._feature_store_id = featurestore_id # for consistency with feature group
self._feature_store_name = featurestore_name
self._version = version
self._description = description
self._labels = labels if labels else []
self._inference_helper_columns = (
inference_helper_columns if inference_helper_columns else []
)
self._training_helper_columns = (
training_helper_columns if training_helper_columns else []
)
self._transformation_functions: List[TransformationFunction] = (
[
TransformationFunction(
self.featurestore_id,
hopsworks_udf=transformation_function,
version=1,
)
if not isinstance(transformation_function, TransformationFunction)
else transformation_function
for transformation_function in transformation_functions
]
if transformation_functions
else []
)
if self._transformation_functions:
self._transformation_functions = FeatureView._sort_transformation_functions(
self._transformation_functions
)
self._features = []
self._feature_view_engine: feature_view_engine.FeatureViewEngine = (
feature_view_engine.FeatureViewEngine(featurestore_id)
)
self._transformation_function_engine: transformation_function_engine.TransformationFunctionEngine = transformation_function_engine.TransformationFunctionEngine(
featurestore_id
)
self._vector_server: Optional[vector_server.VectorServer] = None
self._batch_scoring_server: Optional[vector_server.VectorServer] = None
self._serving_keys = serving_keys if serving_keys else []
self._prefix_serving_key_map = {}
self._primary_keys: Set[str] = set() # Lazy initialized via serving keys
self._vector_db_client = None
self._statistics_engine = statistics_engine.StatisticsEngine(
featurestore_id, self.ENTITY_TYPE
)
self._logging_enabled = logging_enabled
if self._id:
self._init_feature_monitoring_engine()
# last_accessed_training_dataset is only from the perspective of the client itself, and not the backend.
# if multiple clients do training datasets operations, each will have their own view of the last accessed.
# last accessed (read/write) training dataset is not necessarily the newest (highest version).
self._last_accessed_training_dataset = None
def get_last_accessed_training_dataset(self):
return self._last_accessed_training_dataset
def delete(self) -> None:
"""Delete current feature view, all associated metadata and training data.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# delete a feature view
feature_view.delete()
```
!!! danger "Potentially dangerous operation"
This operation drops all metadata associated with **this version** of the
feature view **and** related training dataset **and** materialized data in HopsFS.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
warnings.warn(
"All jobs associated to feature view `{}`, version `{}` will be removed.".format(
self._name, self._version
),
util.JobWarning,
stacklevel=2,
)
self._feature_view_engine.delete(self.name, self.version)
@staticmethod
def clean(
feature_store_id: int, feature_view_name: str, feature_view_version: str
) -> None:
"""
Delete the feature view and all associated metadata and training data.
This can delete corrupted feature view which cannot be retrieved due to a corrupted query for example.
!!! example
```python
# delete a feature view and all associated metadata
from hsfs.feature_view import FeatureView
FeatureView.clean(
feature_store_id=1,
feature_view_name='feature_view_name',
feature_view_version=1
)
```
!!! danger "Potentially dangerous operation"
This operation drops all metadata associated with **this version** of the
feature view **and** related training dataset **and** materialized data in HopsFS.
# Arguments
feature_store_id: int. Id of feature store.
feature_view_name: str. Name of feature view.
feature_view_version: str. Version of feature view.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
if not isinstance(feature_store_id, int):
raise ValueError("`feature_store_id` should be an integer.")
FeatureViewApi(feature_store_id).delete_by_name_version(
feature_view_name, feature_view_version
)
def update(self) -> FeatureView:
"""Update the description of the feature view.
!!! example "Update the feature view with a new description."
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
feature_view.description = "new description"
feature_view.update()
# Description is updated in the metadata. Below should return "new description".
fs.get_feature_view("feature_view_name", 1).description
```
# Returns
`FeatureView` Updated feature view.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
return self._feature_view_engine.update(self)
@usage.method_logger
def init_serving(
self,
training_dataset_version: Optional[int] = None,
external: Optional[bool] = None,
options: Optional[Dict[str, Any]] = None,
init_sql_client: Optional[bool] = None,
init_rest_client: bool = False,
reset_rest_client: bool = False,
config_rest_client: Optional[Dict[str, Any]] = None,
default_client: Optional[Literal["sql", "rest"]] = None,
**kwargs,
) -> None:
"""Initialise feature view to retrieve feature vector from online and offline feature store.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# initialise feature view to retrieve a feature vector
feature_view.init_serving(training_dataset_version=1)
```
# Arguments
training_dataset_version: int, optional. Default to be 1 for online feature store.
Transformation statistics are fetched from training dataset and applied to the feature vector.
external: boolean, optional. If set to True, the connection to the
online feature store is established using the same host as
for the `host` parameter in the [`hsfs.connection()`](connection_api.md#connection) method.
If set to False, the online feature store storage connector is used which relies on the private IP.
Defaults to True if connection to Hopsworks is established from external environment (e.g AWS
Sagemaker or Google Colab), otherwise to False.
init_sql_client: boolean, optional. By default the sql client is initialised if no
client is specified to match legacy behaviour. If set to True, this ensure the online store
sql client is initialised, otherwise if init_rest_client is set to true it will
skip initialising the sql client.
init_rest_client: boolean, defaults to False. By default the rest client is not initialised.
If set to True, this ensure the online store rest client is initialised. Pass additional configuration
options via the rest_config parameter. Set reset_rest_client to True to reset the rest client.
default_client: string, optional. Which client to default to if both are initialised. Defaults to None.
options: Additional options as key/value pairs for configuring online serving engine.
* key: kwargs of SqlAlchemy engine creation (See: https://docs.sqlalchemy.org/en/20/core/engines.html#sqlalchemy.create_engine).
For example: `{"pool_size": 10}`
reset_rest_client: boolean, defaults to False. If set to True, the rest client will be reset and reinitialised with provided configuration.
config_rest_client: dictionary, optional. Additional configuration options for the rest client. If the client is already initialised,
this will be ignored. Options include:
* `host`: string, optional. The host of the online store. Dynamically set if not provided.
* `port`: int, optional. The port of the online store. Defaults to 4406.
* `verify_certs`: boolean, optional. Verify the certificates of the online store server. Defaults to True.
* `api_key`: string, optional. The API key to authenticate with the online store. The api key must be
provided if initialising the rest client in an internal environment.
* `timeout`: int, optional. The timeout for the rest client in seconds. Defaults to 2.
* `use_ssl`: boolean, optional. Use SSL to connect to the online store. Defaults to True.
"""
# initiate batch scoring server
# `training_dataset_version` should not be set if `None` otherwise backend will look up the td.
try:
self.init_batch_scoring(training_dataset_version)
except ValueError as e:
# In 3.3 or before, td version is set to 1 by default.
# For backward compatibility, if a td version is required, set it to 1.
if "Training data version is required for transformation" in str(e):
self.init_batch_scoring(1)
else:
raise e
# Compatibility with 3.7
if init_sql_client is None:
init_sql_client = kwargs.get("init_online_store_sql_client", None)
if init_rest_client is False:
init_rest_client = kwargs.get("init_online_store_rest_client", False)
if training_dataset_version is None:
training_dataset_version = 1
warnings.warn(
"No training dataset version was provided to initialise serving. Defaulting to version 1.",
util.VersionWarning,
stacklevel=1,
)
# initiate single vector server
self._vector_server = vector_server.VectorServer(
self._featurestore_id,
self._features,
training_dataset_version,
serving_keys=self._serving_keys,
skip_fg_ids=set([fg.id for fg in self._get_embedding_fgs()]),
feature_view_name=self._name,
feature_view_version=self._version,
feature_store_name=self._feature_store_name,
)
self._vector_server.init_serving(
entity=self,
external=external,
inference_helper_columns=True,
options=options,
init_sql_client=init_sql_client,
init_rest_client=init_rest_client,
reset_rest_client=reset_rest_client,
config_rest_client=config_rest_client,
default_client=default_client,
)
self._prefix_serving_key_map = dict(
[
(f"{sk.prefix}{sk.feature_name}", sk)
for sk in self._vector_server.serving_keys
]
)
if len(self._get_embedding_fgs()) > 0:
self._vector_db_client = VectorDbClient(
self.query, serving_keys=self._serving_keys
)
@staticmethod
def _sort_transformation_functions(
transformation_functions: List[TransformationFunction],
) -> List[TransformationFunction]:
"""
Function that sorts transformation functions in the order of the output column names.
The list of transformation functions are sorted based on the output columns names to maintain consistent ordering.
# Arguments
transformation_functions: `List[TransformationFunction]`. List of transformation functions to be sorted
# Returns
`List[TransformationFunction]`: List of transformation functions to be sorted
"""
return sorted(transformation_functions, key=lambda x: x.output_column_names[0])
def init_batch_scoring(
self,
training_dataset_version: Optional[int] = None,
) -> None:
"""Initialise feature view to retrieve feature vector from offline feature store.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# initialise feature view to retrieve feature vector from offline feature store
feature_view.init_batch_scoring(training_dataset_version=1)
# get batch data
batch_data = feature_view.get_batch_data(...)
```
# Arguments
training_dataset_version: int, optional. Default to be None. Transformation statistics
are fetched from training dataset and applied to the feature vector.
"""
self._batch_scoring_server = vector_server.VectorServer(
self._featurestore_id,
self._features,
training_dataset_version,
serving_keys=self._serving_keys,
skip_fg_ids=set([fg.id for fg in self._get_embedding_fgs()]),
feature_view_name=self._name,
feature_view_version=self._version,
feature_store_name=self._feature_store_name,
)
self._batch_scoring_server.init_batch_scoring(self)
def get_batch_query(
self,
start_time: Optional[Union[str, int, datetime, date]] = None,
end_time: Optional[Union[str, int, datetime, date]] = None,
) -> str:
"""Get a query string of the batch query.
!!! example "Batch query for the last 24 hours"
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# set up dates
import datetime
start_date = (datetime.datetime.now() - datetime.timedelta(hours=24))
end_date = (datetime.datetime.now())
# get a query string of batch query
query_str = feature_view.get_batch_query(
start_time=start_date,
end_time=end_date
)
# print query string
print(query_str)
```
# Arguments
start_time: Start event time for the batch query, inclusive. Optional. Strings should be formatted in one of the following formats `%Y-%m-%d`, `%Y-%m-%d %H`, `%Y-%m-%d %H:%M`,
`%Y-%m-%d %H:%M:%S`, or `%Y-%m-%d %H:%M:%S.%f`. Int, i.e Unix Epoch should be in seconds.
end_time: End event time for the batch query, exclusive. Optional. Strings should be formatted in one of the following formats `%Y-%m-%d`, `%Y-%m-%d %H`, `%Y-%m-%d %H:%M`,
`%Y-%m-%d %H:%M:%S`, or `%Y-%m-%d %H:%M:%S.%f`. Int, i.e Unix Epoch should be in seconds.
# Returns
`str`: batch query
"""
return self._feature_view_engine.get_batch_query_string(
self,
start_time,
end_time,
training_dataset_version=self._batch_scoring_server.training_dataset_version
if self._batch_scoring_server
else None,
)
def get_feature_vector(
self,
entry: Dict[str, Any],
passed_features: Optional[Dict[str, Any]] = None,
external: Optional[bool] = None,
return_type: Literal["list", "polars", "numpy", "pandas"] = "list",
allow_missing: bool = False,
force_rest_client: bool = False,
force_sql_client: bool = False,
transformed: Optional[bool] = True,
) -> Union[List[Any], pd.DataFrame, np.ndarray, pl.DataFrame]:
"""Returns assembled feature vector from online feature store.
Call [`feature_view.init_serving`](#init_serving) before this method if the following configurations are needed.
1. The training dataset version of the transformation statistics
2. Additional configurations of online serving engine
!!! warning "Missing primary key entries"
If the provided primary key `entry` can't be found in one or more of the feature groups
used by this feature view the call to this method will raise an exception.
Alternatively, setting `allow_missing` to `True` returns a feature vector with missing values.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# get assembled serving vector as a python list
feature_view.get_feature_vector(
entry = {"pk1": 1, "pk2": 2}
)
# get assembled serving vector as a pandas dataframe
feature_view.get_feature_vector(
entry = {"pk1": 1, "pk2": 2},
return_type = "pandas"
)
# get assembled serving vector as a numpy array
feature_view.get_feature_vector(
entry = {"pk1": 1, "pk2": 2},
return_type = "numpy"
)
```
!!! example "Get feature vector with user-supplied features"
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# the application provides a feature value 'app_attr'
app_attr = ...
# get a feature vector
feature_view.get_feature_vector(
entry = {"pk1": 1, "pk2": 2},
passed_features = { "app_feature" : app_attr }
)
```
# Arguments
entry: dictionary of feature group primary key and values provided by serving application.
Set of required primary keys is [`feature_view.primary_keys`](#primary_keys)
If the required primary keys is not provided, it will look for name
of the primary key in feature group in the entry.
passed_features: dictionary of feature values provided by the application at runtime.
They can replace features values fetched from the feature store as well as
providing feature values which are not available in the feature store.
external: boolean, optional. If set to True, the connection to the
online feature store is established using the same host as
for the `host` parameter in the [`hsfs.connection()`](connection_api.md#connection) method.
If set to False, the online feature store storage connector is used
which relies on the private IP. Defaults to True if connection to Hopsworks is established from
external environment (e.g AWS Sagemaker or Google Colab), otherwise to False.
return_type: `"list"`, `"pandas"`, `"polars"` or `"numpy"`. Defaults to `"list"`.
force_rest_client: boolean, defaults to False. If set to True, reads from online feature store
using the REST client if initialised.
force_sql_client: boolean, defaults to False. If set to True, reads from online feature store
using the SQL client if initialised.
allow_missing: Setting to `True` returns feature vectors with missing values.
transformed: Setting to `False` returns the untransformed feature vectors.
# Returns
`list`, `pd.DataFrame`, `polars.DataFrame` or `np.ndarray` if `return type` is set to `"list"`, `"pandas"`, `"polars"` or `"numpy"`
respectively. Defaults to `list`.
Returned `list`, `pd.DataFrame`, `polars.DataFrame` or `np.ndarray` contains feature values related to provided primary keys,
ordered according to positions of this features in the feature view query.
# Raises
`Exception`. When primary key entry cannot be found in one or more of the feature groups used by this
feature view.
"""
if self._vector_server is None:
self.init_serving(external=external)
vector_db_features = None
if self._vector_db_client:
vector_db_features = self._get_vector_db_result(entry)
return self._vector_server.get_feature_vector(
entry=entry,
return_type=return_type,
passed_features=passed_features,
allow_missing=allow_missing,
vector_db_features=vector_db_features,
force_rest_client=force_rest_client,
force_sql_client=force_sql_client,
transformed=transformed,
)
def get_feature_vectors(
self,
entry: List[Dict[str, Any]],
passed_features: Optional[List[Dict[str, Any]]] = None,
external: Optional[bool] = None,
return_type: Literal["list", "polars", "numpy", "pandas"] = "list",
allow_missing: bool = False,
force_rest_client: bool = False,
force_sql_client: bool = False,
transformed: Optional[bool] = True,
) -> Union[List[List[Any]], pd.DataFrame, np.ndarray, pl.DataFrame]:
"""Returns assembled feature vectors in batches from online feature store.
Call [`feature_view.init_serving`](#init_serving) before this method if the following configurations are needed.
1. The training dataset version of the transformation statistics
2. Additional configurations of online serving engine
!!! warning "Missing primary key entries"
If any of the provided primary key elements in `entry` can't be found in any
of the feature groups, no feature vector for that primary key value will be
returned.
If it can be found in at least one but not all feature groups used by
this feature view the call to this method will raise an exception.
Alternatively, setting `allow_missing` to `True` returns feature vectors with missing values.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# get assembled serving vectors as a python list of lists
feature_view.get_feature_vectors(
entry = [
{"pk1": 1, "pk2": 2},
{"pk1": 3, "pk2": 4},
{"pk1": 5, "pk2": 6}
]
)
# get assembled serving vectors as a pandas dataframe
feature_view.get_feature_vectors(
entry = [
{"pk1": 1, "pk2": 2},
{"pk1": 3, "pk2": 4},
{"pk1": 5, "pk2": 6}
],
return_type = "pandas"
)
# get assembled serving vectors as a numpy array
feature_view.get_feature_vectors(
entry = [
{"pk1": 1, "pk2": 2},
{"pk1": 3, "pk2": 4},
{"pk1": 5, "pk2": 6}
],
return_type = "numpy"
)
```
# Arguments
entry: a list of dictionary of feature group primary key and values provided by serving application.
Set of required primary keys is [`feature_view.primary_keys`](#primary_keys)
If the required primary keys is not provided, it will look for name
of the primary key in feature group in the entry.
passed_features: a list of dictionary of feature values provided by the application at runtime.
They can replace features values fetched from the feature store as well as
providing feature values which are not available in the feature store.
external: boolean, optional. If set to True, the connection to the
online feature store is established using the same host as
for the `host` parameter in the [`hsfs.connection()`](connection_api.md#connection) method.
If set to False, the online feature store storage connector is used
which relies on the private IP. Defaults to True if connection to Hopsworks is established from
external environment (e.g AWS Sagemaker or Google Colab), otherwise to False.
return_type: `"list"`, `"pandas"`, `"polars"` or `"numpy"`. Defaults to `"list"`.
force_sql_client: boolean, defaults to False. If set to True, reads from online feature store
using the SQL client if initialised.
force_rest_client: boolean, defaults to False. If set to True, reads from online feature store
using the REST client if initialised.
allow_missing: Setting to `True` returns feature vectors with missing values.
transformed: Setting to `False` returns the untransformed feature vectors.
# Returns
`List[list]`, `pd.DataFrame`, `polars.DataFrame` or `np.ndarray` if `return type` is set to `"list", `"pandas"`,`"polars"` or `"numpy"`
respectively. Defaults to `List[list]`.
Returned `List[list]`, `pd.DataFrame`, `polars.DataFrame` or `np.ndarray` contains feature values related to provided primary
keys, ordered according to positions of this features in the feature view query.
# Raises
`Exception`. When primary key entry cannot be found in one or more of the feature groups used by this
feature view.
"""
if self._vector_server is None:
self.init_serving(external=external, init_rest_client=force_rest_client)
vector_db_features = []
if self._vector_db_client:
for _entry in entry:
vector_db_features.append(self._get_vector_db_result(_entry))
return self._vector_server.get_feature_vectors(
entries=entry,
return_type=return_type,
passed_features=passed_features,
allow_missing=allow_missing,
vector_db_features=vector_db_features,
force_rest_client=force_rest_client,
force_sql_client=force_sql_client,
transformed=transformed,
)
def get_inference_helper(
self,
entry: Dict[str, Any],
external: Optional[bool] = None,
return_type: Literal["pandas", "dict", "polars"] = "pandas",
force_rest_client: bool = False,
force_sql_client: bool = False,
) -> Union[pd.DataFrame, pl.DataFrame, Dict[str, Any]]:
"""Returns assembled inference helper column vectors from online feature store.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# get assembled inference helper column vector
feature_view.get_inference_helper(
entry = {"pk1": 1, "pk2": 2}
)
```
# Arguments
entry: dictionary of feature group primary key and values provided by serving application.
Set of required primary keys is [`feature_view.primary_keys`](#primary_keys)
external: boolean, optional. If set to True, the connection to the
online feature store is established using the same host as
for the `host` parameter in the [`hsfs.connection()`](connection_api.md#connection) method.
If set to False, the online feature store storage connector is used
which relies on the private IP. Defaults to True if connection to Hopsworks is established from
external environment (e.g AWS Sagemaker or Google Colab), otherwise to False.
return_type: `"pandas"`, `"polars"` or `"dict"`. Defaults to `"pandas"`.
# Returns
`pd.DataFrame`, `polars.DataFrame` or `dict`. Defaults to `pd.DataFrame`.
# Raises
`Exception`. When primary key entry cannot be found in one or more of the feature groups used by this
feature view.
"""
if self._vector_server is None:
self.init_serving(external=external, init_rest_client=force_rest_client)
return self._vector_server.get_inference_helper(
entry, return_type, force_rest_client, force_sql_client
)
def get_inference_helpers(
self,
entry: List[Dict[str, Any]],
external: Optional[bool] = None,
return_type: Literal["pandas", "dict", "polars"] = "pandas",
force_sql_client: bool = False,
force_rest_client: bool = False,
) -> Union[List[Dict[str, Any]], pd.DataFrame, pl.DataFrame]:
"""Returns assembled inference helper column vectors in batches from online feature store.
!!! warning "Missing primary key entries"
If any of the provided primary key elements in `entry` can't be found in any
of the feature groups, no inference helper column vectors for that primary key value will be
returned.
If it can be found in at least one but not all feature groups used by
this feature view the call to this method will raise an exception.
!!! example
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# get assembled inference helper column vectors
feature_view.get_inference_helpers(
entry = [
{"pk1": 1, "pk2": 2},
{"pk1": 3, "pk2": 4},
{"pk1": 5, "pk2": 6}
]
)
```
# Arguments
entry: a list of dictionary of feature group primary key and values provided by serving application.
Set of required primary keys is [`feature_view.primary_keys`](#primary_keys)
external: boolean, optional. If set to True, the connection to the
online feature store is established using the same host as
for the `host` parameter in the [`hsfs.connection()`](connection_api.md#connection) method.
If set to False, the online feature store storage connector is used
which relies on the private IP. Defaults to True if connection to Hopsworks is established from
external environment (e.g AWS Sagemaker or Google Colab), otherwise to False.
return_type: `"pandas"`, `"polars"` or `"dict"`. Defaults to `"pandas"`.
# Returns
`pd.DataFrame`, `polars.DataFrame` or `List[Dict[str, Any]]`. Defaults to `pd.DataFrame`.
Returned `pd.DataFrame` or `List[dict]` contains feature values related to provided primary
keys, ordered according to positions of this features in the feature view query.
# Raises
`Exception`. When primary key entry cannot be found in one or more of the feature groups used by this
feature view.
"""
if self._vector_server is None:
self.init_serving(external=external, init_rest_client=force_rest_client)
return self._vector_server.get_inference_helpers(
self, entry, return_type, force_rest_client, force_sql_client
)
def _get_vector_db_result(
self,
entry: Dict[str, Any],
) -> Optional[Dict[str, Any]]:
if not self._vector_db_client:
return {}
result_vectors = {}
for join_index, fg in self._vector_db_client.embedding_fg_by_join_index.items():
complete, fg_entry = self._vector_db_client.filter_entry_by_join_index(
entry, join_index
)
if not complete:
# Not retrieving from vector db if entry is not completed
continue
vector_db_features = self._vector_db_client.read(
fg.id,
fg.features,
keys=fg_entry,
index_name=fg.embedding_index.index_name,
)
# if result is not empty
if vector_db_features:
vector_db_features = vector_db_features[0] # get the first result
result_vectors.update(vector_db_features)
return result_vectors
def find_neighbors(
self,
embedding: List[Union[int, float]],
feature: Optional[Feature] = None,
k: Optional[int] = 10,
filter: Optional[Union[Filter, Logic]] = None,
external: Optional[bool] = None,
return_type: Literal["list", "polars", "pandas"] = "list",
) -> List[List[Any]]:
"""
Finds the nearest neighbors for a given embedding in the vector database.
If `filter` is specified, or if embedding feature is stored in default project index,
the number of results returned may be less than k. Try using a large value of k and extract the top k
items from the results if needed.
!!! warning "Duplicate column error in Polars"
If the feature view has duplicate column names, attempting to create a polars DataFrame
will raise an error. To avoid this, set `return_type` to `"list"` or `"pandas"`.
# Arguments
embedding: The target embedding for which neighbors are to be found.
feature: The feature used to compute similarity score. Required only if there
are multiple embeddings (optional).
k: The number of nearest neighbors to retrieve (default is 10).
filter: A filter expression to restrict the search space (optional).
external: boolean, optional. If set to True, the connection to the
online feature store is established using the same host as
for the `host` parameter in the [`hsfs.connection()`](connection_api.md#connection) method.
If set to False, the online feature store storage connector is used
which relies on the private IP. Defaults to True if connection to Hopsworks is established from
external environment (e.g AWS Sagemaker or Google Colab), otherwise to False.
return_type: `"list"`, `"pandas"` or `"polars"`. Defaults to `"list"`.
# Returns
`list`, `pd.DataFrame` or `polars.DataFrame` if `return type` is set to `"list"`, `"pandas"` or
`"polars"` respectively. Defaults to `list`.
!!! Example
```
embedding_index = EmbeddingIndex()
embedding_index.add_embedding(name="user_vector", dimension=3)
fg = fs.create_feature_group(
name='air_quality',
embedding_index=embedding_index,
version=1,
primary_key=['id1'],
online_enabled=True,
)
fg.insert(data)
fv = fs.create_feature_view("air_quality", fg.select_all())
fv.find_neighbors(
[0.1, 0.2, 0.3],
k=5,
)
# apply filter
fg.find_neighbors(
[0.1, 0.2, 0.3],
k=5,
feature=fg.user_vector, # optional
filter=(fg.id1 > 10) & (fg.id1 < 30)
)
```
"""
if self._vector_db_client is None:
self.init_serving(external=external)
results = self._vector_db_client.find_neighbors(
embedding,
feature=(feature if feature else None),
k=k,
filter=filter,
)
if len(results) == 0:
return []
return self._vector_server.get_feature_vectors(
[self._extract_primary_key(res[1]) for res in results],
return_type=return_type,
vector_db_features=[res[1] for res in results],
allow_missing=True,
)
def _extract_primary_key(self, result_key: Dict[str, str]) -> Dict[str, str]:
primary_key_map = {}
for prefix_sk, sk in self._prefix_serving_key_map.items():
if prefix_sk in result_key:
primary_key_map[sk.required_serving_key] = result_key[prefix_sk]
elif sk.feature_name in result_key: # fall back to use raw feature name
primary_key_map[sk.required_serving_key] = result_key[sk.feature_name]
if len(set(self._vector_server.required_serving_keys)) > len(primary_key_map):
raise FeatureStoreException(
f"Failed to get feature vector because required primary key [{', '.join([k for k in set([sk.required_serving_key for sk in self._prefix_serving_key_map.values()]) - primary_key_map.keys()])}] are not present in vector db."
"If the join of the embedding feature group in the query does not have a prefix,"
" try to create a new feature view with prefix attached."
)
return primary_key_map
def _get_embedding_fgs(
self,
) -> Set[feature_group.FeatureGroup]:
return set([fg for fg in self.query.featuregroups if fg.embedding_index])
@usage.method_logger
def get_batch_data(
self,
start_time: Optional[Union[str, int, datetime, date]] = None,
end_time: Optional[Union[str, int, datetime, date]] = None,
read_options: Optional[Dict[str, Any]] = None,
spine: Optional[SplineDataFrameTypes] = None,
primary_key: bool = False,
event_time: bool = False,
inference_helper_columns: bool = False,
dataframe_type: Optional[str] = "default",
transformed: Optional[bool] = True,
**kwargs,
) -> TrainingDatasetDataFrameTypes:
"""Get a batch of data from an event time interval from the offline feature store.
!!! example "Batch data for the last 24 hours"
```python
# get feature store instance
fs = ...
# get feature view instance
feature_view = fs.get_feature_view(...)
# set up dates
import datetime
start_date = (datetime.datetime.now() - datetime.timedelta(hours=24))
end_date = (datetime.datetime.now())
# get a batch of data
df = feature_view.get_batch_data(
start_time=start_date,
end_time=end_date
)
```
!!! warning "Spine Groups/Dataframes"
Spine groups and dataframes are currently only supported with the Spark engine and
Spark dataframes.
# Arguments
start_time: Start event time for the batch query, inclusive. Optional. Strings should be
formatted in one of the following formats `%Y-%m-%d`, `%Y-%m-%d %H`, `%Y-%m-%d %H:%M`, `%Y-%m-%d %H:%M:%S`,
or `%Y-%m-%d %H:%M:%S.%f`. Int, i.e Unix Epoch should be in seconds.
end_time: End event time for the batch query, exclusive. Optional. Strings should be
formatted in one of the following formats `%Y-%m-%d`, `%Y-%m-%d %H`, `%Y-%m-%d %H:%M`, `%Y-%m-%d %H:%M:%S`,
or `%Y-%m-%d %H:%M:%S.%f`. Int, i.e Unix Epoch should be in seconds.
read_options: User provided read options for python engine, defaults to `{}`:
* key `"arrow_flight_config"` to pass a dictionary of arrow flight configurations.
For example: `{"arrow_flight_config": {"timeout": 900}}`