SQL クエリをプログラムで実行する
PySpark では、DataFrame を SQL クエリで簡単に操作できます。SparkSession の sql() 関数を使うと、アプリケーションからプログラム的に SQL クエリを実行し、その結果を別の DataFrame として受け取れます。この演習では、前に作成した DataFrame から一時テーブルを作成し、その一時テーブルから人名を選択するクエリを組み立て、結果を新しい DataFrame に代入します。
ワークスペースにはすでに SparkSession の spark と DataFrame が用意されています。
この演習はコースの一部です
PySparkで学ぶBig Data入門
演習の手順
- 一時テーブル
peopleを作成します。 - 一時テーブル
peopleから人名を選択するqueryを作成します。 - Spark の
queryの結果を新しい DataFramepeople_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.____(____)