-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathsnowflake.py
More file actions
263 lines (222 loc) · 9.86 KB
/
snowflake.py
File metadata and controls
263 lines (222 loc) · 9.86 KB
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
import os
from binascii import hexlify
from datetime import datetime
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple
import pandas as pd
from pydantic import ConfigDict, Field, StrictStr
from feast.entity import Entity
from feast.feature_view import FeatureView
from feast.infra.key_encoding_utils import serialize_entity_key
from feast.infra.online_stores.online_store import OnlineStore
from feast.infra.utils.snowflake.snowflake_utils import (
GetSnowflakeConnection,
execute_snowflake_statement,
get_snowflake_online_store_path,
write_pandas_binary,
)
from feast.protos.feast.types.EntityKey_pb2 import EntityKey as EntityKeyProto
from feast.protos.feast.types.Value_pb2 import Value as ValueProto
from feast.repo_config import FeastConfigBaseModel, RepoConfig
from feast.utils import to_naive_utc
class SnowflakeOnlineStoreConfig(FeastConfigBaseModel):
"""Online store config for Snowflake"""
type: Literal["snowflake.online"] = "snowflake.online"
""" Online store type selector """
config_path: Optional[str] = os.path.expanduser("~/.snowsql/config")
""" Snowflake snowsql config path -- absolute path required (Cant use ~)"""
connection_name: Optional[str] = None
""" Snowflake connector connection name -- typically defined in ~/.snowflake/connections.toml """
account: Optional[str] = None
""" Snowflake deployment identifier -- drop .snowflakecomputing.com """
user: Optional[str] = None
""" Snowflake user name """
password: Optional[str] = None
""" Snowflake password """
role: Optional[str] = None
""" Snowflake role name """
warehouse: Optional[str] = None
""" Snowflake warehouse name """
authenticator: Optional[str] = None
""" Snowflake authenticator name """
private_key: Optional[str] = None
""" Snowflake private key file path"""
private_key_content: Optional[bytes] = None
""" Snowflake private key stored as bytes"""
private_key_passphrase: Optional[str] = None
""" Snowflake private key file passphrase"""
database: StrictStr
""" Snowflake database name """
schema_: Optional[str] = Field("PUBLIC", alias="schema")
""" Snowflake schema name """
model_config = ConfigDict(populate_by_name=True, extra="allow")
class SnowflakeOnlineStore(OnlineStore):
def online_write_batch(
self,
config: RepoConfig,
table: FeatureView,
data: List[
Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]]
],
progress: Optional[Callable[[int], Any]],
) -> None:
assert isinstance(config.online_store, SnowflakeOnlineStoreConfig)
dfs = [None] * len(data)
for i, (entity_key, values, timestamp, created_ts) in enumerate(data):
df = pd.DataFrame(
columns=[
"entity_feature_key",
"entity_key",
"feature_name",
"value",
"event_ts",
"created_ts",
],
index=range(0, len(values)),
)
timestamp = to_naive_utc(timestamp)
if created_ts is not None:
created_ts = to_naive_utc(created_ts)
for j, (feature_name, val) in enumerate(values.items()):
df.loc[j, "entity_feature_key"] = serialize_entity_key(
entity_key,
entity_key_serialization_version=config.entity_key_serialization_version,
) + bytes(feature_name, encoding="utf-8")
df.loc[j, "entity_key"] = serialize_entity_key(
entity_key,
entity_key_serialization_version=config.entity_key_serialization_version,
)
df.loc[j, "feature_name"] = feature_name
df.loc[j, "value"] = val.SerializeToString()
df.loc[j, "event_ts"] = timestamp
df.loc[j, "created_ts"] = created_ts
dfs[i] = df
if dfs:
agg_df = pd.concat(dfs)
# This combines both the data upload plus the overwrite in the same transaction
online_path = get_snowflake_online_store_path(config, table)
with GetSnowflakeConnection(config.online_store, autocommit=False) as conn:
write_pandas_binary(
conn,
agg_df,
table_name=f"[online-transient] {config.project}_{table.name}",
database=f"{config.online_store.database}",
schema=f"{config.online_store.schema_}",
) # special function for writing binary to snowflake
query = f"""
INSERT OVERWRITE INTO {online_path}."[online-transient] {config.project}_{table.name}"
SELECT
"entity_feature_key",
"entity_key",
"feature_name",
"value",
"event_ts",
"created_ts"
FROM
(SELECT
*,
ROW_NUMBER() OVER(PARTITION BY "entity_key","feature_name" ORDER BY "event_ts" DESC, "created_ts" DESC) AS "_feast_row"
FROM
{online_path}."[online-transient] {config.project}_{table.name}")
WHERE
"_feast_row" = 1;
"""
execute_snowflake_statement(conn, query)
conn.commit()
if progress:
progress(len(data))
return None
def online_read(
self,
config: RepoConfig,
table: FeatureView,
entity_keys: List[EntityKeyProto],
requested_features: Optional[List[str]] = None,
) -> List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]]:
assert isinstance(config.online_store, SnowflakeOnlineStoreConfig)
result: List[Tuple[Optional[datetime], Optional[Dict[str, ValueProto]]]] = []
requested_features = requested_features if requested_features else []
# Pre-compute serialized entity keys to avoid redundant serialization
serialized_entity_keys = [
serialize_entity_key(
entity_key,
entity_key_serialization_version=config.entity_key_serialization_version,
)
for entity_key in entity_keys
]
entity_fetch_str = ",".join(
[
(
"TO_BINARY("
+ hexlify(
serialized_entity_key + bytes(feature, encoding="utf-8")
).__str__()[1:]
+ ")"
)
for serialized_entity_key in serialized_entity_keys
for feature in requested_features
]
)
online_path = get_snowflake_online_store_path(config, table)
with GetSnowflakeConnection(config.online_store) as conn:
query = f"""
SELECT
"entity_key", "feature_name", "value", "event_ts"
FROM
{online_path}."[online-transient] {config.project}_{table.name}"
WHERE
"entity_feature_key" IN ({entity_fetch_str})
"""
df = execute_snowflake_statement(conn, query).fetch_pandas_all()
for entity_key_bin in serialized_entity_keys:
res = {}
res_ts = None
for index, row in df[df["entity_key"] == entity_key_bin].iterrows():
val = ValueProto()
val.ParseFromString(row["value"])
res[row["feature_name"]] = val
res_ts = row["event_ts"].to_pydatetime()
if not res:
result.append((None, None))
else:
result.append((res_ts, res))
return result
def update(
self,
config: RepoConfig,
tables_to_delete: Sequence[FeatureView],
tables_to_keep: Sequence[FeatureView],
entities_to_delete: Sequence[Entity],
entities_to_keep: Sequence[Entity],
partial: bool,
):
assert isinstance(config.online_store, SnowflakeOnlineStoreConfig)
with GetSnowflakeConnection(config.online_store) as conn:
for table in tables_to_keep:
online_path = get_snowflake_online_store_path(config, table)
query = f"""
CREATE TRANSIENT TABLE IF NOT EXISTS {online_path}."[online-transient] {config.project}_{table.name}" (
"entity_feature_key" BINARY,
"entity_key" BINARY,
"feature_name" VARCHAR,
"value" BINARY,
"event_ts" TIMESTAMP,
"created_ts" TIMESTAMP
)
"""
execute_snowflake_statement(conn, query)
for table in tables_to_delete:
online_path = get_snowflake_online_store_path(config, table)
query = f'DROP TABLE IF EXISTS {online_path}."[online-transient] {config.project}_{table.name}"'
execute_snowflake_statement(conn, query)
def teardown(
self,
config: RepoConfig,
tables: Sequence[FeatureView],
entities: Sequence[Entity],
):
assert isinstance(config.online_store, SnowflakeOnlineStoreConfig)
with GetSnowflakeConnection(config.online_store) as conn:
for table in tables:
online_path = get_snowflake_online_store_path(config, table)
query = f'DROP TABLE IF EXISTS {online_path}."[online-transient] {config.project}_{table.name}"'
execute_snowflake_statement(conn, query)