在 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.____(____)