-
Notifications
You must be signed in to change notification settings - Fork 0
/
etl.py
302 lines (258 loc) · 8.82 KB
/
etl.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
import pandas as pd
import psycopg2
import datetime
from dateutil import relativedelta
from loguru import logger
from psycopg2 import sql
import time
from constants import *
db_config = {
"database": "test_db",
"user": "admin",
"password": "root",
"host": "localhost",
"port": "5432",
}
def build_url(filename):
return f"https://d37ci6vzurychx.cloudfront.net/trip-data/{filename}"
def build_connection():
conn = psycopg2.connect(
database=db_config["database"],
user=db_config["user"],
password=db_config["password"],
host=db_config["host"],
port=db_config["port"],
)
logger.info("Connection Successful to PostgreSQL")
return conn
def check_table_exists(cur, table_name):
# Check if the table exists
result = cur.execute(
"""
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_name = %s
) AS table_existence;
""",
[table_name],
)
result = cur.fetchall()
return bool(result[0][0])
def initialize_database():
# Connect with postgressql
logger.info("Starting Initialization")
conn = build_connection()
cur = conn.cursor()
conn.set_session(autocommit=True)
if check_table_exists(cur, TRIPS_TABLE_NAME):
logger.info(f"Table {TRIPS_TABLE_NAME} exists")
else:
# Create table
command = sql.SQL(
"""
CREATE TABLE IF NOT EXISTS {} (
VendorID INTEGER,
tpep_pickup_datetime TIMESTAMP NOT NULL,
tpep_dropoff_datetime TIMESTAMP NOT NULL,
PASSENGER_COUNT FLOAT,
TRIP_DISTANCE FLOAT,
RATECODEID FLOAT,
store_and_fwd_flag TEXT,
PULOCATIONID INTEGER,
DOLOCATIONID INTEGER,
PAYMENT_TYPE INTEGER,
FARE_AMOUNT FLOAT,
EXTRA FLOAT,
MTA_TAX FLOAT,
TIP_AMOUNT FLOAT,
TOLLS_AMOUNT FLOAT,
IMPROVEMENT_SURCHARGE FLOAT,
TOTAL_AMOUNT FLOAT,
CONGESTION_SURCHARGE FLOAT,
airport_fee TEXT,
year_month TEXT,
processed_time TIMESTAMP NOT NULL
);
CREATE TABLE IF NOT EXISTS {} (
year_month TEXT,
PULocationID INTEGER,
DOLocationID INTEGER,
trip_count_array INTEGER[][],
avg_amount_array FLOAT[][]
);
"""
).format(
sql.Identifier(TRIPS_TABLE_NAME),
sql.Identifier(AGGREGATED_TRIPS_TABLE_NAME),
)
cur.execute(command)
logger.info(f"Initializing with Jan 2020 data")
run_etl(datetime.datetime(2020, 1, 1), cur)
logger.info("Ending Initialization")
conn.commit()
cur.close()
conn.close()
def is_data_available(cur, formatted_year_month):
cur.execute(
sql.SQL(
"""
SELECT
%s in (SELECT DISTINCT year_month FROM {}) as is_stored
"""
).format(sql.Identifier(AGGREGATED_TRIPS_TABLE_NAME)),
[formatted_year_month],
)
return cur.fetchall()[0][0]
def has_exceeded_database_limit(cur):
cur.execute(
sql.SQL(
"""
SELECT
COUNT(DISTINCT year_month)
FROM {}
"""
).format(sql.Identifier(AGGREGATED_TRIPS_TABLE_NAME))
)
number_of_months = cur.fetchall()[0][0]
logger.info(f"Number of unique year_month: {number_of_months}")
return number_of_months == DATABASE_LIMIT
def query_aggregated_trips_data(input_date):
logger.info(f"Querying data with input: {input_date}")
formatted_year_month = input_date.strftime(YEAR_MONTH_FORMAT)
# Connect with postgressql
conn = build_connection()
cur = conn.cursor()
conn.set_session(autocommit=True)
# Validate data availability & database limit
if not is_data_available(cur, formatted_year_month):
logger.info("Data is not available")
if has_exceeded_database_limit(cur):
logger.info("Database will exceed limit")
delete_data(cur)
run_etl(input_date, cur)
# Query data
logger.info(f"Querying data")
cur.execute(
sql.SQL(
"""
SELECT
PULocationID,
DOLocationID,
trip_count_array,
avg_amount_array
FROM {}
WHERE year_month = %s
"""
).format(sql.Identifier(AGGREGATED_TRIPS_TABLE_NAME)),
[formatted_year_month],
)
result = cur.fetchall()
# logger.info(f"Queried result: {result[0] if len(result) > 0 else 'None'}")
conn.commit()
cur.close()
conn.close()
logger.info("Closed PostgreSQL Connection")
logger.info(f"Ending Query")
return {"data": result, "columns": [i[0] for i in cur.description]}
def delete_data(cur):
logger.info("Deleting Data")
cur.execute(
sql.SQL(
"""
DELETE FROM {} WHERE processed_time = (SELECT MIN(processed_time) FROM {})
"""
).format(sql.Identifier(TRIPS_TABLE_NAME), sql.Identifier(TRIPS_TABLE_NAME))
)
logger.info("Finish Deleting")
def import_data(df, cur, target_table):
from io import StringIO
buffer = StringIO()
df.to_csv(buffer, index=False, header=False, sep="\t")
buffer.seek(0)
cur.copy_from(buffer, target_table, sep="\t")
def build_long_array_metrics(row, metric_col):
monthly_arr = []
metrics_length = len(row[metric_col])
i = 0
for day in range(1, 32):
day_arr = []
if day in row["day"]:
for hour in range(24):
hourly_metric = 0
if (
i < metrics_length
and row["hour"][i] == hour
and row["day"][i] == day
):
hourly_metric = row[metric_col][i]
i += 1
day_arr.append(str(hourly_metric))
else:
day_arr = ["0" for _ in range(24)]
monthly_arr.append("{" + ",".join(day_arr) + "}")
if i != metrics_length:
print("hailat")
return "{" + ",".join(monthly_arr) + "}"
def run_etl(date, cur):
start_time = time.time()
formatted_year_month = date.strftime("%Y-%m")
logger.info(f"Starting ETL for {formatted_year_month} data...")
start_date = date.replace(day=1)
end_date = start_date + relativedelta.relativedelta(months=1)
filename = f"yellow_tripdata_{formatted_year_month}.parquet"
dataset_url = build_url(filename)
# Read file from website
df = pd.read_parquet(dataset_url, engine="pyarrow").fillna(0)
# Need to handle data validation
if "PULocationID" not in df.columns or "DOLocationID" not in df.columns:
raise Exception("No location data")
df = df[
(df[PICKUP_DATETIME_COL] >= start_date) & (df[PICKUP_DATETIME_COL] < end_date)
]
df["year_month"] = formatted_year_month
df["hour"] = df[PICKUP_DATETIME_COL].dt.hour
df["day"] = df[PICKUP_DATETIME_COL].dt.day
df["processed_time"] = datetime.datetime.now()
# Aggregate data
agg_df = (
df.groupby(["day", "hour", "PULocationID", "DOLocationID"]).agg(
trip_count=(PICKUP_DATETIME_COL, "count"),
avg_amount=(TOTAL_AMOUNT_COL, "mean"),
)
).reset_index()
grouped_agg_df = (
agg_df.groupby(["PULocationID", "DOLocationID"])
.agg({"day": list, "hour": list, "trip_count": list, "avg_amount": list})
.reset_index()
)
raw_data = {
"year_month": [formatted_year_month] * len(grouped_agg_df),
"PULocationID": grouped_agg_df["PULocationID"],
"DOLocationID": grouped_agg_df["DOLocationID"],
"trip_count_array": grouped_agg_df.apply(
lambda row: build_long_array_metrics(row, "trip_count"), axis=1
),
"avg_amount_array": grouped_agg_df.apply(
lambda row: build_long_array_metrics(row, "avg_amount"), axis=1
),
}
aggregated_trips_df = pd.DataFrame(raw_data)
# Import fact data
df = df.drop(columns=["hour", "day"])
logger.info(f"Start Copying {len(df)} rows to {TRIPS_TABLE_NAME}...")
import_data(df, cur, TRIPS_TABLE_NAME)
logger.info("Done Copying...")
# Import aggregate data
logger.info(
f"Start Copying {len(aggregated_trips_df)} rows to {AGGREGATED_TRIPS_TABLE_NAME}..."
)
import_data(
aggregated_trips_df,
cur,
AGGREGATED_TRIPS_TABLE_NAME,
)
logger.info("Done Copying...")
logger.info(f"Ending ETL... Time taken: {time.time() - start_time}")
# initialize_database()
# query_aggregated_trips_data(datetime.datetime(2020, 2, 12))