forked from logicalclocks/hopsworks-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeature_group.py
4534 lines (3931 loc) · 182 KB
/
feature_group.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 2020 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 copy
import json
import logging
import time
import warnings
from datetime import date, datetime
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
Optional,
Tuple,
TypeVar,
Union,
)
if TYPE_CHECKING:
import great_expectations
import avro.schema
import hsfs.expectation_suite
import humps
import numpy as np
import pandas as pd
from hopsworks_common.client.exceptions import FeatureStoreException, RestAPIError
from hopsworks_common.core.constants import HAS_POLARS
from hsfs import (
engine,
feature,
feature_group_writer,
tag,
user,
util,
)
from hsfs import (
feature_store as feature_store_mod,
)
from hsfs import (
storage_connector as sc,
)
from hsfs.constructor import filter, query
from hsfs.constructor.filter import Filter, Logic
from hsfs.core import (
deltastreamer_jobconf,
expectation_suite_engine,
explicit_provenance,
external_feature_group_engine,
feature_group_engine,
feature_monitoring_config_engine,
feature_monitoring_result_engine,
feature_store_api,
great_expectation_engine,
job_api,
spine_group_engine,
statistics_engine,
validation_report_engine,
validation_result_engine,
)
from hsfs.core import feature_monitoring_config as fmc
from hsfs.core import feature_monitoring_result as fmr
from hsfs.core.constants import (
HAS_CONFLUENT_KAFKA,
HAS_GREAT_EXPECTATIONS,
)
from hsfs.core.job import Job
from hsfs.core.variable_api import VariableApi
from hsfs.core.vector_db_client import VectorDbClient
# if great_expectations is not installed, we will default to using native Hopsworks class as return values
from hsfs.decorators import typechecked, uses_great_expectations
from hsfs.embedding import EmbeddingIndex
from hsfs.ge_validation_result import ValidationResult
from hsfs.hopsworks_udf import HopsworksUdf
from hsfs.online_config import OnlineConfig
from hsfs.statistics import Statistics
from hsfs.statistics_config import StatisticsConfig
from hsfs.transformation_function import TransformationFunction, TransformationType
from hsfs.validation_report import ValidationReport
if HAS_GREAT_EXPECTATIONS:
import great_expectations
if HAS_CONFLUENT_KAFKA:
import confluent_kafka
if HAS_POLARS:
import polars as pl
_logger = logging.getLogger(__name__)
@typechecked
class FeatureGroupBase:
def __init__(
self,
name: Optional[str],
version: Optional[int],
featurestore_id: Optional[int],
location: Optional[str],
event_time: Optional[Union[str, int, date, datetime]] = None,
online_enabled: bool = False,
id: Optional[int] = None,
embedding_index: Optional[EmbeddingIndex] = None,
expectation_suite: Optional[
Union[
hsfs.expectation_suite.ExpectationSuite,
great_expectations.core.ExpectationSuite,
Dict[str, Any],
]
] = None,
online_topic_name: Optional[str] = None,
topic_name: Optional[str] = None,
notification_topic_name: Optional[str] = None,
deprecated: bool = False,
online_config: Optional[
Union[
OnlineConfig,
Dict[str, Any],
]
] = None,
storage_connector: Union[sc.StorageConnector, Dict[str, Any]] = None,
path: Optional[str] = None,
**kwargs,
) -> None:
self._version = version
self._name = name
self.event_time = event_time
self._online_enabled = online_enabled
self._location = location
self._id = id
self._subject = None
self._online_topic_name = online_topic_name
self._topic_name = topic_name
self._notification_topic_name = notification_topic_name
self._deprecated = deprecated
self._feature_store_id = featurestore_id
self._feature_store = None
self._variable_api: VariableApi = VariableApi()
self._path = path
if storage_connector is not None and isinstance(storage_connector, dict):
self._storage_connector = sc.StorageConnector.from_response_json(
storage_connector
)
else:
self._storage_connector: "sc.StorageConnector" = storage_connector
self._online_config = (
OnlineConfig.from_response_json(online_config)
if isinstance(online_config, dict)
else online_config
)
self._multi_part_insert: bool = False
self._embedding_index = embedding_index
# use setter for correct conversion
self.expectation_suite = expectation_suite
self._feature_group_engine: Optional[
feature_group_engine.FeatureGroupEngine
] = None
self._statistics_engine: statistics_engine.StatisticsEngine = (
statistics_engine.StatisticsEngine(featurestore_id, self.ENTITY_TYPE)
)
self._great_expectation_engine: great_expectation_engine.GreatExpectationEngine = great_expectation_engine.GreatExpectationEngine(
featurestore_id
)
if self._id is not None:
if expectation_suite:
self._expectation_suite._init_expectation_engine(
feature_store_id=featurestore_id, feature_group_id=self._id
)
self._expectation_suite_engine: Optional[
expectation_suite_engine.ExpectationSuiteEngine
] = expectation_suite_engine.ExpectationSuiteEngine(
feature_store_id=featurestore_id, feature_group_id=self._id
)
self._validation_report_engine: Optional[
validation_report_engine.ValidationReportEngine
] = validation_report_engine.ValidationReportEngine(
featurestore_id, self._id
)
self._validation_result_engine: Optional[
validation_result_engine.ValidationResultEngine
] = validation_result_engine.ValidationResultEngine(
featurestore_id, self._id
)
self._feature_monitoring_config_engine: Optional[
feature_monitoring_config_engine.FeatureMonitoringConfigEngine
] = feature_monitoring_config_engine.FeatureMonitoringConfigEngine(
feature_store_id=featurestore_id,
feature_group_id=self._id,
)
self._feature_monitoring_result_engine: feature_monitoring_result_engine.FeatureMonitoringResultEngine = feature_monitoring_result_engine.FeatureMonitoringResultEngine(
feature_store_id=self._feature_store_id,
feature_group_id=self._id,
)
self.check_deprecated()
def check_deprecated(self) -> None:
if self.deprecated:
warnings.warn(
f"Feature Group `{self._name}`, version `{self._version}` is deprecated",
stacklevel=1,
)
def delete(self) -> None:
"""Drop the entire feature group along with its feature data.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(
name='bitcoin_price',
version=1
)
# delete the feature group
fg.delete()
```
!!! danger "Potentially dangerous operation"
This operation drops all metadata associated with **this version** of the
feature group **and** all the feature data in offline and online storage
associated with it.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
warnings.warn(
"All jobs associated to feature group `{}`, version `{}` will be removed.".format(
self._name, self._version
),
util.JobWarning,
stacklevel=1,
)
self._feature_group_engine.delete(self)
def select_all(
self,
include_primary_key: Optional[bool] = True,
include_event_time: Optional[bool] = True,
) -> query.Query:
"""Select all features along with primary key and event time from the feature group and return a query object.
The query can be used to construct joins of feature groups or create a
feature view.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instances
fg1 = fs.get_or_create_feature_group(...)
fg2 = fs.get_or_create_feature_group(...)
# construct the query
query = fg1.select_all().join(fg2.select_all())
# show first 5 rows
query.show(5)
# select all features exclude primary key and event time
from hsfs.feature import Feature
fg = fs.create_feature_group(
"fg",
features=[
Feature("id", type="string"),
Feature("ts", type="bigint"),
Feature("f1", type="date"),
Feature("f2", type="double")
],
primary_key=["id"],
event_time="ts")
query = fg.select_all()
query.features
# [Feature('id', ...), Feature('ts', ...), Feature('f1', ...), Feature('f2', ...)]
query = fg.select_all(include_primary_key=False, include_event_time=False)
query.features
# [Feature('f1', ...), Feature('f2', ...)]
```
# Arguments
include_primary_key: If True, include primary key of the feature group
to the feature list. Defaults to True.
include_event_time: If True, include event time of the feature group
to the feature list. Defaults to True.
# Returns
`Query`. A query object with all features of the feature group.
"""
if include_event_time and include_primary_key:
return query.Query(
left_feature_group=self,
left_features=self._features,
feature_store_name=self._feature_store_name,
feature_store_id=self._feature_store_id,
)
elif include_event_time:
return self.select_except(self.primary_key)
elif include_primary_key:
return self.select_except([self.event_time])
else:
return self.select_except(self.primary_key + [self.event_time])
def select_features(
self,
) -> query.Query:
"""Select all the features in the feature group and return a query object.
Queries define the schema of Feature View objects which can be used to
create Training Datasets, read from the Online Feature Store, and more. They can
also be composed to create more complex queries using the `join` method.
!!! info
This method does not select the primary key and event time of the feature group.
Use `select_all` to include them.
Note that primary keys do not need to be included in the query to allow joining
on them.
!!! example
```python
# connect to the Feature Store
fs = hopsworks.login().get_feature_store()
# Some dataframe to create the feature group with
# both an event time and a primary key column
my_df.head()
+------------+------------+------------+------------+
| id | feature_1 | ... | ts |
+------------+------------+------------+------------+
| 8 | 8 | | 15 |
| 3 | 3 | ... | 6 |
| 1 | 1 | | 18 |
+------------+------------+------------+------------+
# Create the Feature Group instances
fg1 = fs.create_feature_group(
name = "fg1",
version=1,
primary_key=["id"],
event_time="ts",
)
# Insert data to the feature group.
fg1.insert(my_df)
# select all features from `fg1` excluding primary key and event time
query = fg1.select_features()
# show first 3 rows
query.show(3)
# Output, no id or ts columns
+------------+------------+------------+
| feature_1 | feature_2 | feature_3 |
+------------+------------+------------+
| 8 | 7 | 15 |
| 3 | 1 | 6 |
| 1 | 2 | 18 |
+------------+------------+------------+
```
!!! example
```python
# connect to the Feature Store
fs = hopsworks.login().get_feature_store()
# Get the Feature Group from the previous example
fg1 = fs.get_feature_group("fg1", 1)
# Some dataframe to create another feature group
# with a primary key column
+------------+------------+------------+
| id_2 | feature_6 | feature_7 |
+------------+------------+------------+
| 8 | 11 | |
| 3 | 4 | ... |
| 1 | 9 | |
+------------+------------+------------+
# join the two feature groups on their indexes, `id` and `id_2`
# but does not include them in the query
query = fg1.select_features().join(fg2.select_features(), left_on="id", right_on="id_2")
# show first 5 rows
query.show(3)
# Output
+------------+------------+------------+------------+------------+
| feature_1 | feature_2 | feature_3 | feature_6 | feature_7 |
+------------+------------+------------+------------+------------+
| 8 | 7 | 15 | 11 | 15 |
| 3 | 1 | 6 | 4 | 3 |
| 1 | 2 | 18 | 9 | 20 |
+------------+------------+------------+------------+------------+
```
# Returns
`Query`. A query object with all features of the feature group.
"""
query = self.select_except(self.primary_key + [self.event_time])
_logger.info(
f"Using {[f.name for f in query.features]} as features for the query."
"To include primary key and event time use `select_all`."
)
return query
def select(self, features: List[Union[str, feature.Feature]]) -> query.Query:
"""Select a subset of features of the feature group and return a query object.
The query can be used to construct joins of feature groups or create a
feature view with a subset of features of the feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
from hsfs.feature import Feature
fg = fs.create_feature_group(
"fg",
features=[
Feature("id", type="string"),
Feature("ts", type="bigint"),
Feature("f1", type="date"),
Feature("f2", type="double")
],
primary_key=["id"],
event_time="ts")
# construct query
query = fg.select(["id", "f1"])
query.features
# [Feature('id', ...), Feature('f1', ...)]
```
# Arguments
features: A list of `Feature` objects or feature names as
strings to be selected.
# Returns
`Query`: A query object with the selected features of the feature group.
"""
return query.Query(
left_feature_group=self,
left_features=features,
feature_store_name=self._feature_store_name,
feature_store_id=self._feature_store_id,
)
def select_except(
self, features: Optional[List[Union[str, feature.Feature]]] = None
) -> query.Query:
"""Select all features including primary key and event time feature
of the feature group except provided `features` and return a query object.
The query can be used to construct joins of feature groups or create a
feature view with a subset of features of the feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
from hsfs.feature import Feature
fg = fs.create_feature_group(
"fg",
features=[
Feature("id", type="string"),
Feature("ts", type="bigint"),
Feature("f1", type="date"),
Feature("f2", type="double")
],
primary_key=["id"],
event_time="ts")
# construct query
query = fg.select_except(["ts", "f1"])
query.features
# [Feature('id', ...), Feature('f1', ...)]
```
# Arguments
features: A list of `Feature` objects or feature names as
strings to be excluded from the selection. Defaults to [],
selecting all features.
# Returns
`Query`: A query object with the selected features of the feature group.
"""
if features:
except_features = [
f.name if isinstance(f, feature.Feature) else f for f in features
]
return query.Query(
left_feature_group=self,
left_features=[
f for f in self._features if f.name not in except_features
],
feature_store_name=self._feature_store_name,
feature_store_id=self._feature_store_id,
)
else:
return self.select_all()
def filter(self, f: Union[filter.Filter, filter.Logic]) -> query.Query:
"""Apply filter to the feature group.
Selects all features and returns the resulting `Query` with the applied filter.
!!! example
```python
from hsfs.feature import Feature
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.filter(Feature("weekly_sales") > 1000)
```
If you are planning to join the filtered feature group later on with another
feature group, make sure to select the filtered feature explicitly from the
respective feature group:
!!! example
```python
fg.filter(fg.feature1 == 1).show(10)
```
Composite filters require parenthesis and symbols for logical operands (e.g. `&`, `|`, ...):
!!! example
```python
fg.filter((fg.feature1 == 1) | (fg.feature2 >= 2))
```
# Arguments
f: Filter object.
# Returns
`Query`. The query object with the applied filter.
"""
return self.select_all().filter(f)
def add_tag(self, name: str, value: Any) -> None:
"""Attach a tag to a feature group.
A tag consists of a <name,value> pair. Tag names are unique identifiers across the whole cluster.
The value of a tag can be any valid json - primitives, arrays or json objects.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.add_tag(name="example_tag", value="42")
```
# Arguments
name: Name of the tag to be added.
value: Value of the tag to be added.
# Raises
`hsfs.client.exceptions.RestAPIError` in case the backend fails to add the tag.
"""
self._feature_group_engine.add_tag(self, name, value)
def delete_tag(self, name: str) -> None:
"""Delete a tag attached to a feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.delete_tag("example_tag")
```
# Arguments
name: Name of the tag to be removed.
# Raises
`hsfs.client.exceptions.RestAPIError` in case the backend fails to delete the tag.
"""
self._feature_group_engine.delete_tag(self, name)
def get_tag(self, name: str) -> tag.Tag:
"""Get the tags of a feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg_tag_value = fg.get_tag("example_tag")
```
# Arguments
name: Name of the tag to get.
# Returns
tag value
# Raises
`hsfs.client.exceptions.RestAPIError` in case the backend fails to retrieve the tag.
"""
return self._feature_group_engine.get_tag(self, name)
def get_tags(self) -> Dict[str, tag.Tag]:
"""Retrieves all tags attached to a feature group.
# Returns
`Dict[str, obj]` of tags.
# Raises
`hsfs.client.exceptions.RestAPIError` in case the backend fails to retrieve the tags.
"""
return self._feature_group_engine.get_tags(self)
def get_parent_feature_groups(self) -> explicit_provenance.Links:
"""Get the parents of this feature group, based on explicit provenance.
Parents are feature groups or external feature groups. These feature
groups can be accessible, deleted or inaccessible.
For deleted and inaccessible feature groups, only a minimal information is
returned.
# Returns
`ProvenanceLinks`: Object containing the section of provenance graph requested.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
return self._feature_group_engine.get_parent_feature_groups(self)
def get_storage_connector_provenance(self):
"""Get the parents of this feature group, based on explicit provenance.
Parents are storage connectors. These storage connector can be accessible,
deleted or inaccessible.
For deleted and inaccessible storage connector, only a minimal information is
returned.
# Returns
`ExplicitProvenance.Links`: the storage connector used to generated this
feature group
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
return self._feature_group_engine.get_storage_connector_provenance(self)
def get_storage_connector(self):
"""Get the storage connector using this feature group, based on explicit
provenance. Only the accessible storage connector is returned.
For more items use the base method - get_storage_connector_provenance
# Returns
`StorageConnector: Storage connector.
"""
storage_connector_provenance = self.get_storage_connector_provenance()
if (
storage_connector_provenance.inaccessible
or storage_connector_provenance.deleted
):
_logger.info(
"The parent storage connector is deleted or inaccessible. For more details access `get_storage_connector_provenance`"
)
if storage_connector_provenance.accessible:
return storage_connector_provenance.accessible[0]
else:
return None
def get_generated_feature_views(self) -> explicit_provenance.Links:
"""Get the generated feature view using this feature group, based on explicit
provenance. These feature views can be accessible or inaccessible. Explicit
provenance does not track deleted generated feature view links, so deleted
will always be empty.
For inaccessible feature views, only a minimal information is returned.
# Returns
`ProvenanceLinks`: Object containing the section of provenance graph requested.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
return self._feature_group_engine.get_generated_feature_views(self)
def get_generated_feature_groups(self) -> explicit_provenance.Links:
"""Get the generated feature groups using this feature group, based on explicit
provenance. These feature groups can be accessible or inaccessible. Explicit
provenance does not track deleted generated feature group links, so deleted
will always be empty.
For inaccessible feature groups, only a minimal information is returned.
# Returns
`ProvenanceLinks`: Object containing the section of provenance graph requested.
# Raises
`hsfs.client.exceptions.RestAPIError`.
"""
return self._feature_group_engine.get_generated_feature_groups(self)
def get_feature(self, name: str) -> feature.Feature:
"""Retrieve a `Feature` object from the schema of the feature group.
There are several ways to access features of a feature group:
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
# get Feature instanse
fg.feature1
fg["feature1"]
fg.get_feature("feature1")
```
!!! note
Attribute access to features works only for non-reserved names. For example
features named `id` or `name` will not be accessible via `fg.name`, instead
this will return the name of the feature group itself. Fall back on using
the `get_feature` method.
# Arguments:
name: The name of the feature to retrieve
# Returns:
Feature: The feature object
# Raises
`hsfs.client.exceptions.FeatureStoreException`.
"""
try:
return self.__getitem__(name)
except KeyError as err:
raise FeatureStoreException(
f"'FeatureGroup' object has no feature called '{name}'."
) from err
def update_statistics_config(
self,
) -> Union[FeatureGroup, ExternalFeatureGroup, SpineGroup, FeatureGroupBase]:
"""Update the statistics configuration of the feature group.
Change the `statistics_config` object and persist the changes by calling
this method.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.update_statistics_config()
```
# Returns
`FeatureGroup`. The updated metadata object of the feature group.
# Raises
`hsfs.client.exceptions.RestAPIError`.
`hsfs.client.exceptions.FeatureStoreException`.
"""
self._check_statistics_support() # raises an error if stats not supported
self._feature_group_engine.update_statistics_config(self)
return self
def update_description(
self, description: str
) -> Union[FeatureGroupBase, FeatureGroup, ExternalFeatureGroup, SpineGroup]:
"""Update the description of the feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.update_description(description="Much better description.")
```
!!! info "Safe update"
This method updates the feature group description safely. In case of failure
your local metadata object will keep the old description.
# Arguments
description: New description string.
# Returns
`FeatureGroup`. The updated feature group object.
"""
self._feature_group_engine.update_description(self, description)
return self
def update_notification_topic_name(
self, notification_topic_name: str
) -> Union[FeatureGroupBase, ExternalFeatureGroup, SpineGroup, FeatureGroup]:
"""Update the notification topic name of the feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.update_notification_topic_name(notification_topic_name="notification_topic_name")
```
!!! info "Safe update"
This method updates the feature group notification topic name safely. In case of failure
your local metadata object will keep the old notification topic name.
# Arguments
notification_topic_name: Name of the topic used for sending notifications when entries
are inserted or updated on the online feature store. If set to None no notifications are sent.
# Returns
`FeatureGroup`. The updated feature group object.
"""
self._feature_group_engine.update_notification_topic_name(
self, notification_topic_name
)
return self
def update_deprecated(
self, deprecate: bool = True
) -> Union[FeatureGroupBase, FeatureGroup, ExternalFeatureGroup, SpineGroup]:
"""Deprecate the feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.update_deprecated(deprecate=True)
```
!!! info "Safe update"
This method updates the feature group safely. In case of failure
your local metadata object will be kept unchanged.
# Arguments
deprecate: Boolean value identifying if the feature group should be deprecated. Defaults to True.
# Returns
`FeatureGroup`. The updated feature group object.
"""
self._feature_group_engine.update_deprecated(self, deprecate)
return self
def update_features(
self, features: Union[feature.Feature, List[feature.Feature]]
) -> Union[FeatureGroupBase, FeatureGroup, ExternalFeatureGroup, SpineGroup]:
"""Update metadata of features in this feature group.
Currently it's only supported to update the description of a feature.
!!! danger "Unsafe update"
Note that if you use an existing `Feature` object of the schema in the
feature group metadata object, this might leave your metadata object in a
corrupted state if the update fails.
# Arguments
features: `Feature` or list of features. A feature object or list thereof to
be updated.
# Returns
`FeatureGroup`. The updated feature group object.
"""
new_features = []
if isinstance(features, feature.Feature):
new_features.append(features)
elif isinstance(features, list):
for feat in features:
if isinstance(feat, feature.Feature):
new_features.append(feat)
else:
raise TypeError(
"The argument `features` has to be of type `Feature` or "
"a list thereof, but an element is of type: `{}`".format(
type(features)
)
)
else:
raise TypeError(
"The argument `features` has to be of type `Feature` or a list "
"thereof, but is of type: `{}`".format(type(features))
)
self._feature_group_engine.update_features(self, new_features)
return self
def update_feature_description(
self, feature_name: str, description: str
) -> Union[FeatureGroupBase, FeatureGroup, ExternalFeatureGroup, SpineGroup]:
"""Update the description of a single feature in this feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)
fg.update_feature_description(feature_name="min_temp",
description="Much better feature description.")
```
!!! info "Safe update"
This method updates the feature description safely. In case of failure
your local metadata object will keep the old description.
# Arguments
feature_name: Name of the feature to be updated.
description: New description string.
# Returns
`FeatureGroup`. The updated feature group object.
"""
f_copy = copy.deepcopy(self[feature_name])
f_copy.description = description
self._feature_group_engine.update_features(self, [f_copy])
return self
def append_features(
self, features: Union[feature.Feature, List[feature.Feature]]
) -> Union[FeatureGroupBase, FeatureGroup, ExternalFeatureGroup, SpineGroup]:
"""Append features to the schema of the feature group.
!!! example
```python
# connect to the Feature Store
fs = ...
# define features to be inserted in the feature group
features = [
Feature(name="id",type="int",online_type="int"),
Feature(name="name",type="string",online_type="varchar(20)")
]
# get the Feature Group instance
fg = fs.get_or_create_feature_group(...)