在 DataFrame 上執行 SQL
在 PySpark 中,可以用 SQL 查詢輕鬆操作 DataFrame。SparkSession 的 .sql() 方法可讓你以程式方式執行 SQL 查詢,並將結果回傳為另一個 DataFrame。本練習中,你會先把先前建立的 DataFrame 建成一個暫存資料表,接著撰寫查詢,從該暫存表中選出人名,並把查詢結果指定給新的 DataFrame。
提醒你,工作環境中已提供 SparkSession spark 與 DataFrame df。
本練習屬於課程
PySpark 入門
練習說明
- 由
dfDataFrame 建立名稱為"people"的暫存資料表。 - 撰寫查詢,從暫存資料表
people中選出人名。 - 將 Spark 查詢的結果指定給名為
people_df_names的新 DataFrame。 - 列印
people_df_namesDataFrame 的前 10 個人名。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a temporary table "people"
df.____("people")
# Select the names from the temporary table people
query = """SELECT name FROM ____"""
# Assign the result of Spark's query to people_df_names
people_df_names = spark.sql(____)
# Print the top 10 names of the people
people_df_names.____(____)