Skip to content

Commit 0f31d43

Browse files
mavysavydavDavid Liu
authored andcommitted
Inferencing of Features in FeatureView and timestamp column of DataSource (#1523)
* Implemented the inferencing. Did cursory runs to make sure it works. More through testing needed. Signed-off-by: David Liu <davidl@twitter.com> * fixed issue with mutable default argument in FeatureView Signed-off-by: David Liu <davidl@twitter.com> * Fix in example_feature_repo_with_inference.py file Signed-off-by: David Liu <davidl@twitter.com> * Added test cases and small fixes. Signed-off-by: David Liu <davidl@twitter.com> * fixed missing import with handling for lint error Signed-off-by: David Liu <davidl@twitter.com> * marked a test that needs bigquery client requesting to be an integration test & added __ rule in inference Signed-off-by: David Liu <davidl@twitter.com> * Code review corrections + BQSource Query arg handling + corresponding test case for it Signed-off-by: David Liu <davidl@twitter.com> * CR corrections Signed-off-by: David Y Liu <davidyliuliu@gmail.com> Co-authored-by: David Liu <davidl@twitter.com>
1 parent ba77796 commit 0f31d43

6 files changed

Lines changed: 332 additions & 14 deletions

File tree

‎sdk/python/feast/data_source.py‎

Lines changed: 96 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,15 @@
1414

1515

1616
import enum
17-
from typing import Dict, Optional
17+
import re
18+
from typing import Callable, Dict, Iterable, Optional, Tuple
1819

20+
from pyarrow.parquet import ParquetFile
21+
22+
from feast import type_map
1923
from feast.data_format import FileFormat, StreamFormat
2024
from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto
25+
from feast.value_type import ValueType
2126

2227

2328
class SourceType(enum.Enum):
@@ -515,11 +520,45 @@ def to_proto(self) -> DataSourceProto:
515520
"""
516521
raise NotImplementedError
517522

523+
def _infer_event_timestamp_column(self, ts_column_type_regex_pattern):
524+
ERROR_MSG_PREFIX = "Unable to infer DataSource event_timestamp_column"
525+
USER_GUIDANCE = "Please specify event_timestamp_column explicitly."
526+
527+
if isinstance(self, FileSource) or isinstance(self, BigQuerySource):
528+
event_timestamp_column, matched_flag = None, False
529+
for col_name, col_datatype in self.get_table_column_names_and_types():
530+
if re.match(ts_column_type_regex_pattern, col_datatype):
531+
if matched_flag:
532+
raise TypeError(
533+
f"""
534+
{ERROR_MSG_PREFIX} due to multiple possible columns satisfying
535+
the criteria. {USER_GUIDANCE}
536+
"""
537+
)
538+
matched_flag = True
539+
event_timestamp_column = col_name
540+
if matched_flag:
541+
return event_timestamp_column
542+
else:
543+
raise TypeError(
544+
f"""
545+
{ERROR_MSG_PREFIX} due to an absence of columns that satisfy the criteria.
546+
{USER_GUIDANCE}
547+
"""
548+
)
549+
else:
550+
raise TypeError(
551+
f"""
552+
{ERROR_MSG_PREFIX} because this DataSource currently does not support this inference.
553+
{USER_GUIDANCE}
554+
"""
555+
)
556+
518557

519558
class FileSource(DataSource):
520559
def __init__(
521560
self,
522-
event_timestamp_column: str,
561+
event_timestamp_column: Optional[str] = None,
523562
file_url: Optional[str] = None,
524563
path: Optional[str] = None,
525564
file_format: FileFormat = None,
@@ -543,12 +582,6 @@ def __init__(
543582
Examples:
544583
>>> FileSource(path="/data/my_features.parquet", event_timestamp_column="datetime")
545584
"""
546-
super().__init__(
547-
event_timestamp_column,
548-
created_timestamp_column,
549-
field_mapping,
550-
date_partition_column,
551-
)
552585
if path is None and file_url is None:
553586
raise ValueError(
554587
'No "path" argument provided. Please set "path" to the location of your file source.'
@@ -561,8 +594,17 @@ def __init__(
561594
)
562595
else:
563596
file_url = path
597+
564598
self._file_options = FileOptions(file_format=file_format, file_url=file_url)
565599

600+
super().__init__(
601+
event_timestamp_column
602+
or self._infer_event_timestamp_column(r"timestamp\[\w\w\]"),
603+
created_timestamp_column,
604+
field_mapping,
605+
date_partition_column,
606+
)
607+
566608
def __eq__(self, other):
567609
if not isinstance(other, FileSource):
568610
raise TypeError("Comparisons should only involve FileSource class objects.")
@@ -609,24 +651,34 @@ def to_proto(self) -> DataSourceProto:
609651

610652
return data_source_proto
611653

654+
@staticmethod
655+
def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]:
656+
return type_map.pa_to_feast_value_type
657+
658+
def get_table_column_names_and_types(self) -> Iterable[Tuple[str, str]]:
659+
schema = ParquetFile(self.path).schema_arrow
660+
return zip(schema.names, map(str, schema.types))
661+
612662

613663
class BigQuerySource(DataSource):
614664
def __init__(
615665
self,
616-
event_timestamp_column: str,
666+
event_timestamp_column: Optional[str] = None,
617667
table_ref: Optional[str] = None,
618668
created_timestamp_column: Optional[str] = "",
619669
field_mapping: Optional[Dict[str, str]] = None,
620670
date_partition_column: Optional[str] = "",
621671
query: Optional[str] = None,
622672
):
673+
self._bigquery_options = BigQueryOptions(table_ref=table_ref, query=query)
674+
623675
super().__init__(
624-
event_timestamp_column,
676+
event_timestamp_column
677+
or self._infer_event_timestamp_column("TIMESTAMP|DATETIME"),
625678
created_timestamp_column,
626679
field_mapping,
627680
date_partition_column,
628681
)
629-
self._bigquery_options = BigQueryOptions(table_ref=table_ref, query=query)
630682

631683
def __eq__(self, other):
632684
if not isinstance(other, BigQuerySource):
@@ -684,6 +736,39 @@ def get_table_query_string(self) -> str:
684736
else:
685737
return f"({self.query})"
686738

739+
@staticmethod
740+
def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]:
741+
return type_map.bq_to_feast_value_type
742+
743+
def get_table_column_names_and_types(self) -> Iterable[Tuple[str, str]]:
744+
from google.cloud import bigquery
745+
746+
client = bigquery.Client()
747+
bq_columns_query = ""
748+
name_type_pairs = []
749+
if self.table_ref is not None:
750+
project_id, dataset_id, table_id = self.table_ref.split(".")
751+
bq_columns_query = f"""
752+
SELECT COLUMN_NAME, DATA_TYPE FROM {project_id}.{dataset_id}.INFORMATION_SCHEMA.COLUMNS
753+
WHERE TABLE_NAME = '{table_id}'
754+
"""
755+
table_schema = (
756+
client.query(bq_columns_query).result().to_dataframe_iterable()
757+
)
758+
for df in table_schema:
759+
name_type_pairs.extend(
760+
list(zip(df["COLUMN_NAME"].to_list(), df["DATA_TYPE"].to_list()))
761+
)
762+
else:
763+
bq_columns_query = f"SELECT * FROM ({self.query}) LIMIT 1"
764+
queryRes = client.query(bq_columns_query).result()
765+
name_type_pairs = [
766+
(schema_field.name, schema_field.field_type)
767+
for schema_field in queryRes.schema
768+
]
769+
770+
return name_type_pairs
771+
687772

688773
class KafkaSource(DataSource):
689774
def __init__(

‎sdk/python/feast/feature_view.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
import re
1415
from datetime import datetime, timedelta
1516
from typing import Dict, List, Optional, Tuple, Union
1617

@@ -55,12 +56,35 @@ def __init__(
5556
self,
5657
name: str,
5758
entities: List[str],
58-
features: List[Feature],
5959
ttl: Optional[Union[Duration, timedelta]],
6060
input: Union[BigQuerySource, FileSource],
61+
features: List[Feature] = [],
6162
tags: Optional[Dict[str, str]] = None,
6263
online: bool = True,
6364
):
65+
if not features:
66+
features = [] # to handle python's mutable default arguments
67+
columns_to_exclude = {
68+
input.event_timestamp_column,
69+
input.created_timestamp_column,
70+
} | set(entities)
71+
72+
for col_name, col_datatype in input.get_table_column_names_and_types():
73+
if col_name not in columns_to_exclude and not re.match(
74+
"^__|__$", col_name
75+
):
76+
features.append(
77+
Feature(
78+
col_name,
79+
input.source_datatype_to_feast_value_type()(col_datatype),
80+
)
81+
)
82+
83+
if not features:
84+
raise ValueError(
85+
f"Could not infer Features for the FeatureView named {name}. Please specify Features explicitly for this FeatureView."
86+
)
87+
6488
cols = [entity for entity in entities] + [feat.name for feat in features]
6589
for col in cols:
6690
if input.field_mapping is not None and col in input.field_mapping.keys():

‎sdk/python/feast/type_map.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ def pa_to_value_type(pa_type: object):
417417
return type_map[pa_type.__str__()]
418418

419419

420-
def pa_to_feast_value_type(value: pa.lib.ChunkedArray) -> ValueType:
420+
def pa_to_feast_value_type(value: Union[pa.lib.ChunkedArray, str]) -> ValueType:
421421
type_map = {
422422
"timestamp[ms]": ValueType.INT64,
423423
"int32": ValueType.INT32,
@@ -435,7 +435,9 @@ def pa_to_feast_value_type(value: pa.lib.ChunkedArray) -> ValueType:
435435
"list<item: binary>": ValueType.BYTES_LIST,
436436
"list<item: bool>": ValueType.BOOL_LIST,
437437
}
438-
return type_map[value.type.__str__()]
438+
return type_map[
439+
value.type.__str__() if isinstance(value, pa.lib.ChunkedArray) else value
440+
]
439441

440442

441443
def pa_column_to_timestamp_proto_column(column: pa.lib.ChunkedArray) -> List[Timestamp]:
@@ -480,3 +482,24 @@ def pa_column_to_proto_column(
480482
]
481483
else:
482484
return [ProtoValue(**{value: x.as_py()}) for x in column]
485+
486+
487+
def bq_to_feast_value_type(bq_type_as_str):
488+
type_map: Dict[ValueType, Union[str, Dict[str, Any]]] = {
489+
"DATETIME": ValueType.STRING, # Update to ValueType.UNIX_TIMESTAMP once #1520 lands.
490+
"TIMESTAMP": ValueType.STRING, # Update to ValueType.UNIX_TIMESTAMP once #1520 lands.
491+
"INTEGER": ValueType.INT64,
492+
"INT64": ValueType.INT64,
493+
"STRING": ValueType.STRING,
494+
"FLOAT": ValueType.DOUBLE,
495+
"FLOAT64": ValueType.DOUBLE,
496+
"BYTES": ValueType.BYTES,
497+
"BOOL": ValueType.BOOL,
498+
"ARRAY<INT64>": ValueType.INT64_LIST,
499+
"ARRAY<FLOAT64>": ValueType.DOUBLE_LIST,
500+
"ARRAY<STRING>": ValueType.STRING_LIST,
501+
"ARRAY<BYTES>": ValueType.BYTES_LIST,
502+
"ARRAY<BOOL>": ValueType.BOOL_LIST,
503+
}
504+
505+
return type_map[bq_type_as_str]
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from google.protobuf.duration_pb2 import Duration
2+
3+
from feast import Entity, FeatureView, ValueType
4+
from feast.data_source import FileSource
5+
6+
driver_hourly_stats = FileSource(
7+
path="%PARQUET_PATH%", # placeholder to be replaced by the test
8+
created_timestamp_column="created",
9+
)
10+
11+
driver = Entity(name="driver_id", value_type=ValueType.INT64, description="driver id",)
12+
13+
# features are inferred from columns of data source
14+
driver_hourly_stats_view = FeatureView(
15+
name="driver_hourly_stats",
16+
entities=["driver_id"],
17+
ttl=Duration(seconds=86400 * 1),
18+
online=True,
19+
input=driver_hourly_stats,
20+
tags={},
21+
)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import contextlib
2+
import tempfile
3+
from datetime import datetime, timedelta
4+
5+
import pandas as pd
6+
import pytest
7+
from google.cloud import bigquery
8+
9+
from feast.data_format import ParquetFormat
10+
from feast.data_source import BigQuerySource, FileSource
11+
12+
13+
@pytest.fixture
14+
def simple_dataset_1() -> pd.DataFrame:
15+
now = datetime.utcnow()
16+
ts = pd.Timestamp(now).round("ms")
17+
data = {
18+
"id": [1, 2, 1, 3, 3],
19+
"float_col": [0.1, 0.2, 0.3, 4, 5],
20+
"int64_col": [1, 2, 3, 4, 5],
21+
"string_col": ["a", "b", "c", "d", "e"],
22+
"ts_1": [
23+
ts,
24+
ts - timedelta(hours=4),
25+
ts - timedelta(hours=3),
26+
ts - timedelta(hours=2),
27+
ts - timedelta(hours=1),
28+
],
29+
}
30+
return pd.DataFrame.from_dict(data)
31+
32+
33+
@contextlib.contextmanager
34+
def prep_file_source(df, event_timestamp_column="") -> FileSource:
35+
with tempfile.NamedTemporaryFile(suffix=".parquet") as f:
36+
f.close()
37+
df.to_parquet(f.name)
38+
file_source = FileSource(
39+
file_format=ParquetFormat(),
40+
file_url=f.name,
41+
event_timestamp_column=event_timestamp_column,
42+
)
43+
yield file_source
44+
45+
46+
def simple_bq_source_using_table_ref_arg(
47+
df, event_timestamp_column=""
48+
) -> BigQuerySource:
49+
client = bigquery.Client()
50+
gcp_project = client.project
51+
bigquery_dataset = "ds"
52+
dataset = bigquery.Dataset(f"{gcp_project}.{bigquery_dataset}")
53+
client.create_dataset(dataset, exists_ok=True)
54+
dataset.default_table_expiration_ms = (
55+
1000
56+
* 60
57+
* 60 # 60 minutes in milliseconds (seems to be minimum limit for gcloud)
58+
)
59+
client.update_dataset(dataset, ["default_table_expiration_ms"])
60+
table_ref = f"{gcp_project}.{bigquery_dataset}.table_1"
61+
62+
job = client.load_table_from_dataframe(
63+
df, table_ref, job_config=bigquery.LoadJobConfig()
64+
)
65+
job.result()
66+
67+
return BigQuerySource(
68+
table_ref=table_ref, event_timestamp_column=event_timestamp_column,
69+
)
70+
71+
72+
def simple_bq_source_using_query_arg(df, event_timestamp_column="") -> BigQuerySource:
73+
bq_source_using_table_ref = simple_bq_source_using_table_ref_arg(
74+
df, event_timestamp_column
75+
)
76+
return BigQuerySource(
77+
query=f"SELECT * FROM {bq_source_using_table_ref.table_ref}",
78+
event_timestamp_column=event_timestamp_column,
79+
)

0 commit comments

Comments
 (0)