DML and PartitioningΒΆ

As part of this section we will continue understanding further concepts related to DML and also get into the details related to partitioning tables. With respect to DML, earlier we have seen how to use LOAD command, now we will see how to use INSERT command primarily to get query results copied into a table.

  • Introduction to Partitioning

  • Creating Tables using Parquet

  • LOAD vs. INSERT

  • Inserting Data using Stage Table

  • Creating Partitioned Tables

  • Adding Partitions to Tables

  • Loading data into Partitions

  • Inserting Data into Partitions

  • Using Dynamic Partition Mode

  • Exercise - Partitioned Tables

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 - Managing Tables - DML and Partitioning").
    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

Unlike Hive, Spark SQL does not support Bucketing which is similar to Hash Partitioning. However, Delta Lake does. Delta Lake is 3rd party library which facilitate us additional capabilities such as ACID transactions on top of Spark Metastore tables

Let us make sure that we have orders table with data as we will be using it to populate partitioned tables very soon.

%%sql

USE itversity_retail
%%sql

SHOW tables
%%sql

DROP TABLE orders
%%sql

SELECT current_database()
%%sql

CREATE TABLE IF NOT EXISTS itversity_retail.orders (
  order_id INT,
  order_date STRING,
  order_customer_id INT,
  order_status STRING
) ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
%%sql

LOAD DATA LOCAL INPATH '/data/retail_db/orders'
    OVERWRITE INTO TABLE orders
%%sql

SELECT count(1) FROM orders