使用 PySpark SQL 與 DataFrame 互動

使用 PySpark 的 Big Data 基礎

Upendra Devisetty

Science Analyst, CyVerse

DataFrame API 與 SQL 查詢

  • 在 PySpark 中,你可透過 DataFrame API 與 SQL 查詢與 SparkSQL 互動

  • DataFrame API 提供針對資料的可程式化領域特定語言(DSL)

  • 以程式方式建立 DataFrame 的轉換與動作更容易

  • SQL 查詢精簡、易懂,且可移植

  • 對 DataFrame 的操作也能用 SQL 查詢完成

使用 PySpark 的 Big Data 基礎

執行 SQL 查詢

  • 使用 SparkSession 的 sql() 方法可執行 SQL 查詢

  • sql() 方法以 SQL 陳述式為引數,回傳結果為 DataFrame

df.createOrReplaceTempView("table1")
df2 = spark.sql("SELECT field1, field2 FROM table1")
df2.collect()
[Row(f1=1, f2='row1'), Row(f1=2, f2='row2'), Row(f1=3, f2='row3')]
使用 PySpark 的 Big Data 基礎

以 SQL 查詢擷取資料

test_df.createOrReplaceTempView("test_table")
query = '''SELECT Product_ID FROM test_table'''
test_product_df = spark.sql(query)
test_product_df.show(5)
+----------+
|Product_ID|
+----------+
| P00069042|
| P00248942|
| P00087842|
| P00085442|
| P00285442|
+----------+
使用 PySpark 的 Big Data 基礎

用 SQL 查詢彙總與分組

test_df.createOrReplaceTempView("test_table")
query = '''SELECT Age, max(Purchase) FROM test_table GROUP BY Age'''
spark.sql(query).show(5)
+-----+-------------+
|  Age|max(Purchase)|
+-----+-------------+
|18-25|        23958|
|26-35|        23961|
| 0-17|        23955|
|46-50|        23960|
|51-55|        23960|
+-----+-------------+
only showing top 5 rows
使用 PySpark 的 Big Data 基礎

用 SQL 查詢篩選欄位

test_df.createOrReplaceTempView("test_table")
query = '''SELECT Age, Purchase, Gender FROM test_table WHERE Purchase > 20000 AND Gender == "F"'''
spark.sql(query).show(5)
+-----+--------+------+
|  Age|Purchase|Gender|
+-----+--------+------+
|36-45|   23792|     F|
|26-35|   21002|     F|
|26-35|   23595|     F|
|26-35|   23341|     F|
|46-50|   20771|     F|
+-----+--------+------+
only showing top 5 rows
使用 PySpark 的 Big Data 基礎

一起來練習吧!

使用 PySpark 的 Big Data 基礎

Preparing Video For Download...