LoginSignup
3
5

More than 5 years have passed since last update.

Apache SparkでDBからWHERE句付きでDataFrameを作成する

Posted at

Apache Sparkで既存のDBMSから
DataFrameを作成するには以下のようなやり方があります。

確認した環境
Windows 10
MySQL 5.7.10 (付属のサンプルデータ worldデータベースのcityテーブルを使用しました)
Apache Spark 1.5.2

JDBCドライバの設定

set SPARK_CLASSPATH=lib\mysql-connector-java-5.1.38-bin.jar

SPARK_CLASSPATHにjdbcドライバのパスを設定します。
Windows環境のためSETコマンドを使用しています。

そしてspark-shellの起動

spark-shell

以下を貼り付けます。

val sc: SparkContext // An existing SparkContext.
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

// this is used to implicitly convert an RDD to a DataFrame.
import sqlContext.implicits._

val options = Map("driver" -> "com.mysql.jdbc.Driver",
"url" -> "jdbc:mysql://localhost:3306/world?user=xxx&password=xxx",
"dbtable" -> "(select * from city where countrycode = 'NLD') as city2")

var jdbcDF = sqlContext.read.format("jdbc").options(options).load()

jdbcDF.count()

dbtabeの項目は、通常テーブル名を指定しますが、上記のように別名をつけることで任意のSQLが書けます。

(select * from city where countrycode = 'NLD') as city2

結果は以下のようになりました。

res0: Long = 28

cityテーブルは実際には、4079レコードありますが、「countrycode = 'NLD'」のもののみ絞り込まれています。
これで不必要なデータをメモリに読み込む必要がなくなりました。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5