Projecting Data¶
Let us understand different aspects of projecting data. We primarily using SELECT
to project the data.
We can project all columns using
*
or some columns using column names.We can provide aliases to a column or expression using
AS
inSELECT
clause.DISTINCT
can be used to get the distinct records from selected columns. We can also useDISTINCT *
to get unique records using all the columns.As of now Spark SQL does not support projecting all but one or few columns. It is supported in Hive. Following will work in hive and it will project all the columns from orders except for order_id.
SET hive.support.quoted.identifiers=none;
SELECT `(order_id)?+.+` FROM 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 - Basic Transformations").
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
%%sql
SELECT * FROM orders LIMIT 10
%%sql
DESCRIBE orders
%%sql
SELECT order_customer_id, order_date, order_status FROM orders LIMIT 10
%%sql
SELECT order_customer_id, date_format(order_date, 'yyyy-MM'), order_status FROM orders LIMIT 10
%%sql
SELECT order_customer_id,
date_format(order_date, 'yyyy-MM') AS order_month,
order_status
FROM orders LIMIT 10
%%sql
SELECT DISTINCT order_status FROM orders
%%sql
SELECT DISTINCT * FROM orders LIMIT 10
Using Spark SQL with Python or Scala
spark.sql("SELECT * FROM orders").show()
spark.sql("DESCRIBE orders").show()
spark.sql("SELECT order_customer_id, order_date, order_status FROM orders").show()
spark.sql("""
SELECT order_customer_id,
date_format(order_date, 'yyyy-MM'),
order_status
FROM orders""").show()
spark.sql("""
SELECT order_customer_id,
date_format(order_date, 'yyyy-MM') AS order_month,
order_status
FROM orders
""").show()
spark.sql("SELECT DISTINCT order_status FROM orders").show()
spark.sql("SELECT DISTINCT * FROM orders").show()