การโต้ตอบกับ DataFrame ด้วย PySpark SQL

Big Data Fundamentals with PySpark

Upendra Devisetty

Science Analyst, CyVerse

DataFrame API กับ SQL queries

  • ใน PySpark สามารถโต้ตอบกับ SparkSQL ได้ผ่าน DataFrame API และ SQL queries

  • DataFrame API มีภาษาเฉพาะทาง (DSL) สำหรับจัดการข้อมูลแบบโปรแกรม

  • การ transform และ action บน DataFrame สร้างด้วยโค้ดได้ง่ายกว่า

  • SQL queries กระชับ เข้าใจง่าย และใช้งานได้หลายแพลตฟอร์ม

  • การดำเนินการบน DataFrame ยังทำผ่าน SQL queries ได้เช่นกัน

Big Data Fundamentals with PySpark

การรัน SQL Queries

  • เมธอด sql() ของ SparkSession ใช้รัน SQL query

  • sql() รับ SQL statement เป็น argument และคืนผลลัพธ์เป็น 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')]
Big Data Fundamentals with PySpark

การดึงข้อมูลด้วย SQL query

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|
+----------+
Big Data Fundamentals with PySpark

การสรุปและจัดกลุ่มข้อมูลด้วย SQL queries

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
Big Data Fundamentals with PySpark

การกรองคอลัมน์ด้วย SQL queries

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
Big Data Fundamentals with PySpark

มาฝึกกันเถอะ!

Big Data Fundamentals with PySpark

Preparing Video For Download...