以编程方式运行 SQL 查询
在 PySpark 中,您可以通过 SQL 查询轻松操作 DataFrame。SparkSession 中的 sql() 函数使应用能够以编程方式运行 SQL 查询,并将结果返回为另一个 DataFrame。在本练习中,您将把先前创建的 DataFrame 注册为一个临时表,然后构造查询,从该临时表中选出人员的姓名,并将结果赋给一个新的 DataFrame。
请记住,您的工作区中已经有 SparkSession spark 和一个可用的 DataFrame。
本练习是课程的一部分
使用 PySpark 的大数据基础
练习说明
- 创建临时表
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.____(____)