Inserting Data into PartitionsΒΆ
Let us understand how to use insert to get data into static partitions in Spark Metastore from existing table called as orders.
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
Let us recap what is covered so far related to partitioned tables.
We have created a table called as orders_part with order_month of type INT as partitioned column.
We have added 4 static partitions for 201307, 201308, 201309 and 201310 using ALTER TABLE command.
Once the table is created and partitions are added we have pre-processed the data to get data into the partitions using LOAD command.
It is not practical to use LOAD command always. We typically use
INSERT
via stage table to copy data into partitioned table.We can pre-create partitions in partitioned tables and insert data into partitions using appropriate
INSERT
command. One need to ensure that required filter condition is applied to get the data relevant to the partition that is being populated.We can also create partitions dynamically which we will see as part of the next topic.
%%sql
USE itversity_retail
%%sql
ALTER TABLE orders_part ADD PARTITION (order_month=201311)
%%sql
SELECT count(1) FROM orders_part
%%sql
INSERT INTO TABLE orders_part PARTITION (order_month=201311)
SELECT * FROM orders WHERE order_date LIKE '2013-11%'
%%sql
SELECT count(1) FROM orders_part
import sys.process._
s"hdfs dfs -ls -R /user/${username}/warehouse/${username}_retail.db/orders_part" !