-
Notifications
You must be signed in to change notification settings - Fork 0
/
etl.py
253 lines (197 loc) · 8.73 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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col, monotonically_increasing_id
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, dayofweek, date_format, from_unixtime
from pyspark.sql.types import LongType
import argparse
# In[ ]:
config = configparser.ConfigParser()
config.read('dl.cfg')
# In[ ]:
os.environ['AWS_ACCESS_KEY_ID']=config['AWS']['ACCESS_KEY_ID']
os.environ['AWS_SECRET_ACCESS_KEY']=config['AWS']['SECRET_ACCESS_KEY']
# In[ ]:
def create_spark_session():
'''
create a spark session supporting hadopp and aws
'''
spark = SparkSession .builder .config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.0") .getOrCreate()
return spark
# In[ ]:
def process_song_data(spark, input_data, output_data):
'''
load and process song json files
input data is the song directory
output data is the output directory for star-schema tables (can be a S3 or HDFS bucket)
input songs files should be stored in a tree hierarchy : <intput_data>/<X>/<Y>/<Z>
with <XYZ> being the first 3 letters of the song track ID
'''
# get filepath to song data file
# assumes songs are stored in a tree hierarchy input_data/<X>/<Y>/<Z>
# with <XYZ> being the 1st 3 letters of the song track ID
# X,Y,Z in {A,...,Z}
song_data = os.path.join(input_data,"song_data", "*","*","*")
# read song data file
df = spark.read.json(song_data)
print("EXTRACT SONGS")
# extract columns to create songs table
songs_table = df.select("song_id",
"title",
"artist_id",
"year",
"duration")
# write songs table to parquet files partitioned by year and artist
out_song = os.path.join(output_data, "SONGS")
songs_table.write.partitionBy("year", "artist_id").mode("overwrite").parquet(out_song)
# extract columns to create artists table
artists_table = df.select("artist_id",
col("artist_name").alias("name"),
col("artist_location").alias("location"),
col("artist_latitude").alias("latitude"),
col("artist_longitude").alias("longitude")
).distinct()
# write artists table to parquet files
out_artist = os.path.join(output_data, "ARTISTS")
artists_table.write.mode("overwrite").parquet(out_artist)
# In[ ]:
def process_log_data(spark, input_data, output_data):
'''
load and process log json files
input data is the log directory
output data is the output directory for star-schema tables (can be a S3 or HDFS bucket)
input logs files should be stored in a tree hierarchy : <input_data>/<year>/<month>
'''
# get filepath to log data file
log_data = os.path.join(input_data, "log_data", "*", "*")
# read log data file
df = spark.read.json(log_data)
print("EXTRACT USERS")
# filter by actions for song plays
df = df.filter("page == 'NextSong' ")
# extract columns for users table
users_table = df.select(col("userId").cast("long").alias("user_id"),
col("firstName").alias("first_name"),
col("lastName").alias("last_name"),
"gender",
"level"
)\
.distinct()\
.orderBy("user_id")
# write users table to parquet files
out_users = os.path.join(output_data, "USERS")
users_table.write.mode("overwrite").parquet(out_users)
# create timestamp column from original timestamp column
get_timestamp = udf(lambda x : int(x / 1000.), LongType() )
df = df.withColumn("timestamp", get_timestamp("ts"))
spark.udf.register("get_timestamp",get_timestamp)
# create datetime column from original timestamp column
#get_datetime = udf()
df = df.withColumn("datetime", from_unixtime("timestamp")) .withColumn("hour", hour("datetime")) .withColumn("day", dayofmonth("datetime")) .withColumn("week", weekofyear("datetime")) .withColumn("month", month("datetime")) .withColumn("year", year("datetime")) .withColumn("weekday", dayofweek("datetime"))
# extract columns to create time table
time_table = df.select("ts", "hour", "day", "week", "month", "year", "weekday") .distinct()
# write time table to parquet files partitioned by year and month
out_time = os.path.join(output_data, "TIMESTAMPS")
time_table.write.partitionBy("year", "month").mode("overwrite").parquet(out_time)
# read in song data to use for songplays table
song_db = os.path.join(output_data, "SONGS")
song_df = spark.read.parquet(song_db)
df.createOrReplaceTempView("lg")
song_df.createOrReplaceTempView("sg")
# extract columns from joined song and log datasets to create songplays table
songplays_table = spark.sql("""
SELECT lg.ts AS start_time,
lg.year AS year,
lg.month AS month,
lg.userId AS user_id,
lg.level,
sg.song_id,
sg.artist_id,
lg.sessionId AS session_id,
lg.location,
lg.userAgent AS user_agent
FROM lg
JOIN sg ON sg.title = lg.song
""")
songplays_table = songplays_table.withColumn("songplay_id", monotonically_increasing_id())
rearrange_col = songplays_table.schema.names[:]
rearrange_col.insert( 0, "songplay_id")
rearrange_col.pop()
songplays_table = songplays_table.select(*rearrange_col)
# write songplays table to parquet files partitioned by year and month
out_songplay = os.path.join(output_data, "SONGPLAYS")
songplays_table.write.partitionBy("year", "month").mode("overwrite").parquet(out_songplay)
# In[ ]:
def main(output_data):
'''
ETL process : create a spark session, load and process song and log data,
write star-schema tables in <output_data> in directories :
SONGS, ARTISTS, USERS, TIMESTAMPS, SONGPLAYS
'''
spark = create_spark_session()
input_data = "s3a://udacity-dend/"
#output_data = "hdfs:///user/sparkify/"
process_song_data(spark, input_data, output_data)
process_log_data(spark, input_data, output_data)
# In[ ]:
def main_local():
'''
for testing purposes : perform the whole ETL process locally
load and process local songs and logs tables,
write the star-schema tables locally
'''
spark = create_spark_session()
input_data = "./"
output_data="/"
print("PROCESS SONGS")
process_song_data(spark, input_data, output_data)
print("PROCESS LOGS")
process_log_data(spark, input_data, output_data)
def main_test(output_data):
'''
quick test of ETL : check that the star-schema tables have been created and are readable
count the number of rows in each table.
'''
spark = create_spark_session()
#output_data = "hdfs:///user/sparkify/"
df_users = spark.read.parquet( os.path.join(output_data, "USERS"))
df_songs = spark.read.parquet(os.path.join(output_data, "SONGS"))
df_artists = spark.read.parquet(os.path.join(output_data, "ARTISTS"))
df_songplays = spark.read.parquet(os.path.join(output_data, "SONGPLAYS"))
df_timestamps = spark.read.parquet(os.path.join(output_data, "TIMESTAMPS"))
print("users : ", df_users.count())
print("songs : ", df_songs.count())
print("artists : ", df_artists.count())
print("timestamps : ", df_timestamps.count())
print("songplays : ", df_songplays.count())
def main_test_local():
'''
test local creation of star-schema table: check that the star-schema tables have been created and are readable.
count the number of rows in each table.
'''
spark = create_spark_session()
df_users = spark.read.parquet("OUT/USERS")
df_songs = spark.read.parquet("OUT/SONGS")
df_artists = spark.read.parquet("OUT/ARTISTS")
df_songplays = spark.read.parquet("OUT/SONGPLAYS")
df_timestamps = spark.read.parquet("OUT/TIMESTAMPS")
print("users : ", df_users.count())
print("songs : ", df_songs.count())
print("artists : ", df_artists.count())
print("timestamps : ", df_timestamps.count())
print("songplays : ", df_songplays.count())
# In[ ]:
if __name__ == "__main__":
#main_local()
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--out", help = "output directory (S3 or HDFS)", required = True)
l_args = parser.parse_args()
print("Outputing tables to ", l_args.out)
# extract songs and logs data, write star-schema tables
main(l_args.out)
# test the
main_test(l_args.out)