-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.ingest_drivers_file.py
81 lines (54 loc) · 2.44 KB
/
4.ingest_drivers_file.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
# Databricks notebook source
# MAGIC %md
# MAGIC ### Ingest drivers.json file
# COMMAND ----------
# MAGIC %md
# MAGIC ##### Step 1 - Read the JSON file using the spark dataframe reader API
# COMMAND ----------
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, DateType
# COMMAND ----------
name_schema = StructType(fields=[StructField("forename", StringType(), True),
StructField("surname", StringType(), True)
])
# COMMAND ----------
drivers_schema = StructType(fields=[StructField("driverId", IntegerType(), False),
StructField("driverRef", StringType(), True),
StructField("number", IntegerType(), True),
StructField("code", StringType(), True),
StructField("name", name_schema),
StructField("dob", DateType(), True),
StructField("nationality", StringType(), True),
StructField("url", StringType(), True)
])
# COMMAND ----------
drivers_df = spark.read \
.schema(drivers_schema) \
.json("/mnt/formula1dl/raw/drivers.json")
# COMMAND ----------
# MAGIC %md
# MAGIC ##### Step 2 - Rename columns and add new columns
# MAGIC 1. driverId renamed to driver_id
# MAGIC 1. driverRef renamed to driver_ref
# MAGIC 1. ingestion date added
# MAGIC 1. name added with concatenation of forename and surname
# COMMAND ----------
from pyspark.sql.functions import col, concat, current_timestamp, lit
# COMMAND ----------
drivers_with_columns_df = drivers_df.withColumnRenamed("driverId", "driver_id") \
.withColumnRenamed("driverRef", "driver_ref") \
.withColumn("ingestion_date", current_timestamp()) \
.withColumn("name", concat(col("name.forename"), lit(" "), col("name.surname")))
# COMMAND ----------
# MAGIC %md
# MAGIC ##### Step 3 - Drop the unwanted columns
# MAGIC 1. name.forename
# MAGIC 1. name.surname
# MAGIC 1. url
# COMMAND ----------
drivers_final_df = drivers_with_columns_df.drop(col("url"))
# COMMAND ----------
# MAGIC %md
# MAGIC ##### Step 4 - Write to output to processed container in parquet format
# COMMAND ----------
drivers_final_df.write.mode("overwrite").parquet("/mnt/formula1dl/processed/drivers")
# COMMAND ----------