始める無料で始める

SQL クエリをプログラムで実行する

PySpark では、DataFrame を SQL クエリで簡単に操作できます。SparkSession の sql() 関数を使うと、アプリケーションからプログラム的に SQL クエリを実行し、その結果を別の DataFrame として受け取れます。この演習では、前に作成した DataFrame から一時テーブルを作成し、その一時テーブルから人名を選択するクエリを組み立て、結果を新しい DataFrame に代入します。

ワークスペースにはすでに SparkSession の spark と DataFrame が用意されています。

この演習はコースの一部です

PySparkで学ぶBig Data入門

コースを見る

演習の手順

  • 一時テーブル people を作成します。
  • 一時テーブル people から人名を選択する query を作成します。
  • Spark の query の結果を新しい DataFrame people_df_names に代入します。
  • people_df_names DataFrame から上位 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.____(____)
コードを編集して実行