Prepare HR DatabaseΒΆ

Let us prepare HR database with EMPLOYEES Table. We will be using this for some of the examples as well as exercises related to Window Functions.

Let us start spark context for this Notebook so that we can execute the code provided. You can sign up for our 10 node state of the art cluster/labs to learn Spark SQL using our unique integrated LMS.

val username = System.getProperty("user.name")
import org.apache.spark.sql.SparkSession

val username = System.getProperty("user.name")
val spark = SparkSession.
    builder.
    config("spark.ui.port", "0").
    config("spark.sql.warehouse.dir", s"/user/${username}/warehouse").
    enableHiveSupport.
    appName(s"${username} | Spark SQL - Windowing Functions").
    master("yarn").
    getOrCreate

If you are going to use CLIs, you can use Spark SQL using one of the 3 approaches.

Using Spark SQL

spark2-sql \
    --master yarn \
    --conf spark.ui.port=0 \
    --conf spark.sql.warehouse.dir=/user/${USER}/warehouse

Using Scala

spark2-shell \
    --master yarn \
    --conf spark.ui.port=0 \
    --conf spark.sql.warehouse.dir=/user/${USER}/warehouse

Using Pyspark

pyspark2 \
    --master yarn \
    --conf spark.ui.port=0 \
    --conf spark.sql.warehouse.dir=/user/${USER}/warehouse
  • Create Database itversity_hr (replace itversity with your OS User Name)

  • Create table employees in itversity_hr database.

  • Load data into the table.

First let us start with creating the database.

%%sql

DROP DATABASE itversity_hr CASCADE
%%sql

CREATE DATABASE itversity_hr
%%sql

USE itversity_hr
%%sql

SELECT current_database()

As the database is created, let us go ahead and add table to it.

%%sql

CREATE TABLE employees (
  employee_id     int,
  first_name      varchar(20),
  last_name       varchar(25),
  email           varchar(25),
  phone_number    varchar(20),
  hire_date       date,
  job_id          varchar(10),
  salary          decimal(8,2),
  commission_pct  decimal(2,2),
  manager_id      int,
  department_id   int
) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'

Let us load the data and validate the table.

%%sql

LOAD DATA LOCAL INPATH '/data/hr_db/employees' 
INTO TABLE employees
%%sql

SELECT * FROM employees LIMIT 10
%%sql

SELECT employee_id, department_id, salary FROM employees LIMIT 10
%%sql

SELECT count(1) FROM employees