以程式方式執行 SQL 查詢
在 PySpark 中,可以用 SQL 查詢輕鬆操作 DataFrame。SparkSession 的 sql() 函式可讓應用程式以程式方式執行 SQL 查詢,並將結果回傳為另一個 DataFrame。在本練習中,你會先把先前建立的 DataFrame 註冊成一個暫存資料表,接著撰寫查詢,從該暫存表選出人的姓名,並將結果指定給一個新的 DataFrame。
請記得,你在工作環境中已經有 SparkSession spark 和一個 DataFrame 可用。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 建立暫存資料表
people。 - 建立一個
query,從暫存資料表people中選出人的姓名。 - 將 Spark 的
query結果指定給新的 DataFrame:people_df_names。 - 列印
people_df_namesDataFrame 中前 10 個人的姓名。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a temporary table "people"
people_df.____("people")
# Construct a query to select the names of the people 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.____(____)