-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathhbase_utils.py
More file actions
221 lines (187 loc) · 7.16 KB
/
hbase_utils.py
File metadata and controls
221 lines (187 loc) · 7.16 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
from typing import List, Optional
from happybase import ConnectionPool
class HbaseConstants:
"""Constants to be used by the Hbase Online Store."""
DEFAULT_COLUMN_FAMILY = "default"
EVENT_TS = "event_ts"
CREATED_TS = "created_ts"
DEFAULT_EVENT_TS = DEFAULT_COLUMN_FAMILY + ":" + EVENT_TS
DEFAULT_CREATED_TS = DEFAULT_COLUMN_FAMILY + ":" + CREATED_TS
@staticmethod
def get_feature_from_col(col):
"""Given the column name, exclude the column family to get the feature name."""
return col.decode("utf-8").split(":")[1]
@staticmethod
def get_col_from_feature(feature):
"""Given the feature name, add the column family to get the column name."""
if isinstance(feature, bytes):
feature = feature.decode("utf-8")
return HbaseConstants.DEFAULT_COLUMN_FAMILY + ":" + feature
class HBaseConnector:
"""
Utils class to manage different Hbase operations.
Attributes:
conn: happybase Connection to connect to hbase.
host: hostname of the hbase thrift server.
port: port in which thrift server is running.
timeout: socket timeout in milliseconds.
"""
def __init__(
self,
pool: Optional[ConnectionPool] = None,
host: Optional[str] = None,
port: Optional[int] = None,
connection_pool_size: int = 4,
):
if pool is None:
self.host = host
self.port = port
self.pool = ConnectionPool(
host=host,
port=port,
size=connection_pool_size,
)
else:
self.pool = pool
def create_table(self, table_name: str, colm_family: List[str]):
"""
Create table in hbase online store.
Arguments:
table_name: Name of the Hbase table.
colm_family: List of names of column families to be created in the hbase table.
"""
cf_dict: dict = {}
for cf in colm_family:
cf_dict[cf] = dict()
with self.pool.connection() as conn:
return conn.create_table(table_name, cf_dict)
def create_table_with_default_cf(self, table_name: str):
"""
Create table in hbase online store with one column family "default".
Arguments:
table_name: Name of the Hbase table.
"""
with self.pool.connection() as conn:
return conn.create_table(table_name, {"default": dict()})
def check_if_table_exist(self, table_name: str):
"""
Check if table exists in hbase.
Arguments:
table_name: Name of the Hbase table.
"""
with self.pool.connection() as conn:
return bytes(table_name, "utf-8") in conn.tables()
def batch(self, table_name: str):
"""
Returns a "Batch" instance that can be used for mass data manipulation in the hbase table.
Arguments:
table_name: Name of the Hbase table.
"""
with self.pool.connection() as conn:
return conn.table(table_name).batch()
def put(self, table_name: str, row_key: str, data: dict):
"""
Store data in the hbase table.
Arguments:
table_name: Name of the Hbase table.
row_key: Row key of the row to be inserted to hbase table.
data: Mapping of column family name:column name to column values
"""
with self.pool.connection() as conn:
table = conn.table(table_name)
table.put(row_key, data)
def row(
self,
table_name: str,
row_key,
columns=None,
timestamp=None,
include_timestamp=False,
):
"""
Fetch a row of data from the hbase table.
Arguments:
table_name: Name of the Hbase table.
row_key: Row key of the row to be inserted to hbase table.
columns: the name of columns that needs to be fetched.
timestamp: timestamp specifies the maximum version the cells can have.
include_timestamp: specifies if (column, timestamp) to be return instead of only column.
"""
with self.pool.connection() as conn:
table = conn.table(table_name)
return table.row(row_key, columns, timestamp, include_timestamp)
def rows(
self,
table_name: str,
row_keys,
columns=None,
timestamp=None,
include_timestamp=False,
):
"""
Fetch multiple rows of data from the hbase table.
Arguments:
table_name: Name of the Hbase table.
row_keys: List of row key of the row to be inserted to hbase table.
columns: the name of columns that needs to be fetched.
timestamp: timestamp specifies the maximum version the cells can have.
include_timestamp: specifies if (column, timestamp) to be return instead of only column.
"""
with self.pool.connection() as conn:
table = conn.table(table_name)
return table.rows(row_keys, columns, timestamp, include_timestamp)
def print_table(self, table_name):
"""Prints the table scanning all the rows of the hbase table."""
with self.pool.connection() as conn:
table = conn.table(table_name)
scan_data = table.scan()
for row_key, cols in scan_data:
print(row_key.decode("utf-8"), cols)
def delete_table(self, table: str):
"""Deletes the hbase table given the table name."""
if self.check_if_table_exist(table):
with self.pool.connection() as conn:
conn.delete_table(table, disable=True)
def close_conn(self):
"""Closes the happybase connection."""
with self.pool.connection() as conn:
conn.close()
def main():
from feast.infra.key_encoding_utils import serialize_entity_key
from feast.protos.feast.types.EntityKey_pb2 import EntityKey
from feast.protos.feast.types.Value_pb2 import Value
pool = ConnectionPool(
host="localhost",
port=9090,
size=2,
)
with pool.connection() as connection:
table = connection.table("test_hbase_driver_hourly_stats")
row_keys = [
serialize_entity_key(
EntityKey(
join_keys=["driver_id"], entity_values=[Value(int64_val=1004)]
),
entity_key_serialization_version=3,
).hex(),
serialize_entity_key(
EntityKey(
join_keys=["driver_id"], entity_values=[Value(int64_val=1005)]
),
entity_key_serialization_version=3,
).hex(),
serialize_entity_key(
EntityKey(
join_keys=["driver_id"], entity_values=[Value(int64_val=1024)]
),
entity_key_serialization_version=3,
).hex(),
]
rows = table.rows(row_keys)
for _, row in rows:
for key, value in row.items():
col_name = bytes.decode(key, "utf-8").split(":")[1]
print(col_name, value)
print()
if __name__ == "__main__":
main()