seratch's weblog in Japanese

About Scala, Java and Ruby programming in Japaense. If you need English information, go to http://blog.seratch.net/

ScalikeJDBC で Redshift に SQL を投げる

Amazon Reshift は PostgreSQL JDBC Driver で接続が可能です。

http://docs.aws.amazon.com/redshift/latest/dg/c_redshift-postgres-jdbc.html

ということは ScalikeJDBC を使ってクエリを投げられるということを意味します。

ということで実際にやってみました。本当にできた!!!

まず Redshift の Cluster は適当に AWS の管理コンソールから作成してください。Available になるまではしばらく時間がかかります。

その間に Security Groups で default の設定に CIDR/IP(アクセス元 IP アドレスの設定)、 EC2 Security Group(この AWS アカウントからのアクセスを許可)の両方の設定を追加しておいてください。このセキュリティ設定が適切にできていないと SQL を実行しようとすると operation timeout になります。

それでは早速 ScalikeJDBC から接続してみましょう。sbt を愛用するあなたは project/Build.scala を準備するだけです。

import sbt._, Keys._
object RedshiftBuild extends Build {
  lazy val scalikejdbcVersion = "1.6.7"
  lazy val root = Project(
    id = "root",
    base = file("."),
    settings = Defaults.defaultSettings ++ Seq(
      organization := "org",
      name := "scalikejdbc-redshift",
      version := "0.1",
      scalaVersion := "2.10.2",
      libraryDependencies ++= Seq(
        "com.github.seratch" %% "scalikejdbc"               % scalikejdbcVersion,
        "com.github.seratch" %% "scalikejdbc-interpolation" % scalikejdbcVersion,
        "postgresql"         %  "postgresql"                % "8.4-702.jdbc4",
        "org.slf4j"          %  "slf4j-simple"              % "1.7.5"
      )
    )
  )
}

これだけ用意して sbt console を立ち上げてください。

import scalikejdbc._, SQLInterpolation._

ConnectionPool.singleton(
  "jdbc:postgresql://***.***.ap-northeast-1.redshift.amazonaws.com:5439/mydb", 
  "username", 
  "password")

implicit val session = AutoSession

sql"create table account(id smallint not null distkey sortkey, name varchar(100))".execute.apply()
sql"insert into account values (1, 'Alice')".execute.apply()
sql"insert into account values (2, 'Bob')".execute.apply()
sql"select id, name from account order by id".map(rs => (rs.int("id"), rs.string("name"))).list.apply()

通常の PostgreSQL を扱うのとほぼ同じ感覚で操作できました。もっといろいろやってみたいですね。

試しに立ち上げた Cluster は停止するのを忘れずに。