Skip to content

Commit 01fd199

Browse files
author
David Liu
committed
Code review corrections + BQSource Query arg handling + corresponding test case for it
Signed-off-by: David Liu <davidl@twitter.com>
1 parent 91bf53b commit 01fd199

5 files changed

Lines changed: 102 additions & 36 deletions

File tree

‎sdk/python/feast/data_source.py‎

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,14 @@
1515

1616
import enum
1717
import re
18-
from typing import Dict, Iterable, Optional, Tuple
18+
from typing import Callable, Dict, Iterable, Optional, Tuple
1919

20-
from google.cloud import bigquery
2120
from pyarrow.parquet import ParquetFile
2221

22+
from feast import type_map
2323
from feast.data_format import FileFormat, StreamFormat
2424
from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto
25+
from feast.value_type import ValueType
2526

2627

2728
class SourceType(enum.Enum):
@@ -519,8 +520,9 @@ def to_proto(self) -> DataSourceProto:
519520
"""
520521
raise NotImplementedError
521522

522-
def infer_event_timestamp_column(self, ts_column_type_regex_pattern):
523+
def _infer_event_timestamp_column(self, ts_column_type_regex_pattern):
523524
ERROR_MSG_PREFIX = "Unable to infer DataSource event_timestamp_column"
525+
USER_GUIDANCE = "Please specify event_timestamp_column explicitly."
524526

525527
if isinstance(self, FileSource) or isinstance(self, BigQuerySource):
526528
event_timestamp_column, matched_flag = None, False
@@ -530,7 +532,7 @@ def infer_event_timestamp_column(self, ts_column_type_regex_pattern):
530532
raise TypeError(
531533
f"""
532534
{ERROR_MSG_PREFIX} due to multiple possible columns satisfying
533-
the criteria.
535+
the criteria. {USER_GUIDANCE}
534536
"""
535537
)
536538
matched_flag = True
@@ -541,12 +543,14 @@ def infer_event_timestamp_column(self, ts_column_type_regex_pattern):
541543
raise TypeError(
542544
f"""
543545
{ERROR_MSG_PREFIX} due to an absence of columns that satisfy the criteria.
546+
{USER_GUIDANCE}
544547
"""
545548
)
546549
else:
547550
raise TypeError(
548551
f"""
549552
{ERROR_MSG_PREFIX} because this DataSource currently does not support this inference.
553+
{USER_GUIDANCE}
550554
"""
551555
)
552556

@@ -595,7 +599,7 @@ def __init__(
595599

596600
super().__init__(
597601
event_timestamp_column
598-
or self.infer_event_timestamp_column(r"timestamp\[\w\w\]"),
602+
or self._infer_event_timestamp_column(r"timestamp\[\w\w\]"),
599603
created_timestamp_column,
600604
field_mapping,
601605
date_partition_column,
@@ -647,6 +651,10 @@ def to_proto(self) -> DataSourceProto:
647651

648652
return data_source_proto
649653

654+
@staticmethod
655+
def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]:
656+
return type_map.pa_to_feast_value_type
657+
650658
def get_table_column_names_and_types(self) -> Iterable[Tuple[str, str]]:
651659
schema = ParquetFile(self.path).schema_arrow
652660
return zip(schema.names, map(str, schema.types))
@@ -666,7 +674,7 @@ def __init__(
666674

667675
super().__init__(
668676
event_timestamp_column
669-
or self.infer_event_timestamp_column("TIMESTAMP|DATETIME"),
677+
or self._infer_event_timestamp_column("TIMESTAMP|DATETIME"),
670678
created_timestamp_column,
671679
field_mapping,
672680
date_partition_column,
@@ -728,21 +736,36 @@ def get_table_query_string(self) -> str:
728736
else:
729737
return f"({self.query})"
730738

739+
@staticmethod
740+
def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]:
741+
return type_map.bq_to_feast_value_type
742+
731743
def get_table_column_names_and_types(self) -> Iterable[Tuple[str, str]]:
732-
assert self.table_ref is not None
733-
name_type_pairs = []
734-
project_id, dataset_id, table_id = self.table_ref.split(".")
735-
bq_columns_query = f"""
736-
SELECT COLUMN_NAME, DATA_TYPE FROM {project_id}.{dataset_id}.INFORMATION_SCHEMA.COLUMNS
737-
WHERE TABLE_NAME = '{table_id}'
738-
"""
744+
from google.cloud import bigquery
739745

740746
client = bigquery.Client()
741-
table_schema = client.query(bq_columns_query).result().to_dataframe_iterable()
742-
for df in table_schema:
743-
name_type_pairs.extend(
744-
list(zip(df["COLUMN_NAME"].to_list(), df["DATA_TYPE"].to_list()))
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()
745757
)
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+
]
746769

747770
return name_type_pairs
748771

‎sdk/python/feast/feature_view.py‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232
from feast.protos.feast.core.FeatureView_pb2 import (
3333
MaterializationInterval as MaterializationIntervalProto,
3434
)
35-
from feast.type_map import bq_to_feast_value_type, pa_to_feast_value_type
3635
from feast.value_type import ValueType
3736

3837

@@ -69,21 +68,21 @@ def __init__(
6968
input.event_timestamp_column,
7069
input.created_timestamp_column,
7170
} | set(entities)
72-
type_converter = (
73-
bq_to_feast_value_type
74-
if isinstance(input, BigQuerySource)
75-
else pa_to_feast_value_type
76-
)
7771

7872
for col_name, col_datatype in input.get_table_column_names_and_types():
7973
if col_name not in columns_to_exclude and not re.match(
8074
"^__|__$", col_name
8175
):
82-
features.append(Feature(col_name, type_converter(col_datatype)))
76+
features.append(
77+
Feature(
78+
col_name,
79+
input.source_datatype_to_feast_value_type()(col_datatype),
80+
)
81+
)
8382

8483
if not features:
8584
raise ValueError(
86-
f"Could not infer Features for the FeatureView named {name}."
85+
f"Could not infer Features for the FeatureView named {name}. Please specify Features explicitly for this FeatureView."
8786
)
8887

8988
cols = [entity for entity in entities] + [feat.name for feat in features]

‎sdk/python/feast/type_map.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -486,10 +486,12 @@ def pa_column_to_proto_column(
486486

487487
def bq_to_feast_value_type(bq_type_as_str):
488488
type_map: Dict[ValueType, Union[str, Dict[str, Any]]] = {
489-
"DATETIME": ValueType.STRING, # Unsure if string is right
490-
"TIMESTAMP": ValueType.STRING, # Unsure if string is right
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.INT32,
491492
"INT64": ValueType.INT64,
492493
"STRING": ValueType.STRING,
494+
"FLOAT": ValueType.FLOAT,
493495
"FLOAT64": ValueType.DOUBLE,
494496
"BYTES": ValueType.BYTES,
495497
"BOOL": ValueType.BOOL,

‎sdk/python/tests/fixtures/data_source_fixtures.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,18 @@ def prep_file_source(df, event_timestamp_column="") -> FileSource:
4343
yield file_source
4444

4545

46-
def prep_bq_source(df, event_timestamp_column="") -> BigQuerySource:
46+
def simple_bq_source_using_table_ref_arg(
47+
df, event_timestamp_column=""
48+
) -> BigQuerySource:
4749
client = bigquery.Client()
4850
gcp_project = client.project
4951
bigquery_dataset = "ds"
5052
dataset = bigquery.Dataset(f"{gcp_project}.{bigquery_dataset}")
5153
client.create_dataset(dataset, exists_ok=True)
5254
dataset.default_table_expiration_ms = (
53-
1000 * 60 * 60 * 24 * 14 # 2 weeks in milliseconds
55+
1000
56+
* 60
57+
* 60 # 60 minutes in milliseconds (seems to be minimum limit for gcloud)
5458
)
5559
client.update_dataset(dataset, ["default_table_expiration_ms"])
5660
table_ref = f"{gcp_project}.{bigquery_dataset}.table_1"
@@ -63,3 +67,13 @@ def prep_bq_source(df, event_timestamp_column="") -> BigQuerySource:
6367
return BigQuerySource(
6468
table_ref=table_ref, event_timestamp_column=event_timestamp_column,
6569
)
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=bq_source_using_table_ref.table_ref,
78+
event_timestamp_column=event_timestamp_column,
79+
)

‎sdk/python/tests/test_feature_store.py‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@
1717

1818
import pytest
1919
from fixtures.data_source_fixtures import simple_dataset_1 # noqa: F401
20-
from fixtures.data_source_fixtures import prep_bq_source, prep_file_source
20+
from fixtures.data_source_fixtures import (
21+
prep_file_source,
22+
simple_bq_source_using_query_arg,
23+
simple_bq_source_using_table_ref_arg,
24+
)
2125
from pytest_lazyfixture import lazy_fixture
2226

2327
from feast.data_format import ParquetFormat
@@ -203,27 +207,46 @@ def test_feature_view_inference_success(test_feature_store, dataframe_source):
203207
entities=["id"],
204208
ttl=timedelta(minutes=5),
205209
online=True,
206-
input=prep_bq_source(dataframe_source, "ts_1"),
210+
input=simple_bq_source_using_table_ref_arg(dataframe_source, "ts_1"),
211+
tags={},
212+
)
213+
214+
fv3 = FeatureView(
215+
name="fv3",
216+
entities=["id"],
217+
ttl=timedelta(minutes=5),
218+
online=True,
219+
input=simple_bq_source_using_query_arg(dataframe_source, "ts_1"),
207220
tags={},
208221
)
209222

210-
test_feature_store.apply([fv1, fv2]) # Register Feature Views
223+
test_feature_store.apply([fv1, fv2, fv3]) # Register Feature Views
211224
feature_view_1 = test_feature_store.list_feature_views()[0]
212225
feature_view_2 = test_feature_store.list_feature_views()[1]
226+
feature_view_3 = test_feature_store.list_feature_views()[2]
213227

214228
actual_file_source = {
215229
(feature.name, feature.dtype) for feature in feature_view_1.features
216230
}
217-
actual_bq_source = {
231+
actual_bq_using_table_ref_arg_source = {
218232
(feature.name, feature.dtype) for feature in feature_view_2.features
219233
}
234+
actual_bq_using_query_arg_source = {
235+
(feature.name, feature.dtype) for feature in feature_view_3.features
236+
}
220237
expected = {
221238
("float_col", ValueType.DOUBLE),
222239
("int64_col", ValueType.INT64),
223240
("string_col", ValueType.STRING),
224241
}
242+
expected2 = { # parsing with the "query" param in bq sources uses different code path
243+
("float_col", ValueType.FLOAT),
244+
("int64_col", ValueType.INT32),
245+
("string_col", ValueType.STRING),
246+
}
225247

226-
assert expected == actual_file_source == actual_bq_source
248+
assert expected == actual_file_source == actual_bq_using_table_ref_arg_source
249+
assert expected2 == actual_bq_using_query_arg_source
227250

228251

229252
@pytest.mark.integration
@@ -298,10 +321,15 @@ def test_apply_feature_view_integration(test_feature_store):
298321
def test_data_source_ts_col_inference_success(dataframe_source):
299322
with prep_file_source(df=dataframe_source) as file_source:
300323
actual_file_source = file_source.event_timestamp_column
301-
actual_bq_source = prep_bq_source(dataframe_source).event_timestamp_column
324+
actual_bq_1 = simple_bq_source_using_table_ref_arg(
325+
dataframe_source
326+
).event_timestamp_column
327+
actual_bq_2 = simple_bq_source_using_query_arg(
328+
dataframe_source
329+
).event_timestamp_column
302330
expected = "ts_1"
303331

304-
assert expected == actual_file_source == actual_bq_source
332+
assert expected == actual_file_source == actual_bq_1 == actual_bq_2
305333

306334

307335
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)