使用 PySpark SQL 操作 DataFrame

使用 PySpark 的大数据基础

Upendra Devisetty

Science Analyst, CyVerse

DataFrame API 与 SQL 查询

  • 在 PySpark 中,可通过 DataFrame API 和 SQL 查询使用 SparkSQL

  • DataFrame API 提供用于数据的领域特定语言(DSL)

  • DataFrame 的转换与操作便于以编程方式构建

  • SQL 查询更简洁、易懂,且可移植

  • 对 DataFrame 的操作也可用 SQL 实现

使用 PySpark 的大数据基础

执行 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 的大数据基础

用 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 的大数据基础

用 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 的大数据基础

用 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 的大数据基础

开始练习!

使用 PySpark 的大数据基础

Preparing Video For Download...