Rubyからrbhiveを使ってhiveserver2にhqlを投げてみる
Rubyからrbhiveを使って、
hiveserver2にhqlを投げる方法についてメモです。
このメモは、localhostにhiveをセットアップしている前提です。
mac上でのhiveのセットアップ方法については、
次のエントリを参考にしてください。
Mac上でのhiveセットアップ手順(mysql上にmetastoreを作成)
http://takemikami.com/2016/04/20/Machivemysqlmetastore.html
hiveserver2の起動
まずhiveserver2を起動します。
macでhomebrewを使ってinstallしている場合は、以下のようにして起動します。
$ $(brew --prefix hive)/bin/hiveserver2
rubyからの接続
rbhiveのインストール
作業用ディレクトリに移動した後、以下のようにGemfileを準備します。
$ bundle init
Gemfileを編集して、rbhive-1.0.3.preを追記します。
Gemfile
source "https://rubygems.org"
gem 'rbhive', '1.0.3.pre'
以下のようにして、rbhiveをインストールします。
$ bundle install --path vendor/bundle
サンプルプログラムの準備と実行
hiverserver2に接続するサンプルプログラムを作成します。
sample.rb
require 'rbhive'
RBHive.tcli_connect('127.0.0.1', 10000, {
hive_version: 10,
transport: :sasl,
sasl_params: {username: "#{`whoami`.chop}"}
}) do |connection|
# テーブルを作成
resp = connection.execute("create table if not exists foo(v1 int, v2 string)")
p resp
# レコードをinsert
resp = connection.execute("insert into foo(v1, v2) values (1, 'hoge'),(2, 'fuga')")
p resp
# select、結果を表示
resp = connection.fetch("select * from foo")
resp.each do |row|
p row
end
end
コメントにも書いているように、このサンプルは以下の処理を行います。
- テーブルの作成
- レコードのinsert
- selectの実行と、結果の表示
以下のように、サンプルを実行します。
$ bundle exec ruby sample.rb
※省略※
Connecting to HiveServer2 127.0.0.1 on port 10000
Executing Hive Query: create table if not exists foo(v1 int, v2 string)
<Hive2::Thrift::TExecuteStatementResp status:<Hive2::Thrift::TStatus statusCode:SUCCESS_STATUS (0)>, ※省略※
Executing Hive Query: insert into foo(v1, v2) values (1, 'hoge'),(2, 'fuga')
<Hive2::Thrift::TExecuteStatementResp status:<Hive2::Thrift::TStatus statusCode:SUCCESS_STATUS (0)>, ※省略※
Executing Hive Query: select * from foo
{:"foo.v1"=>"1", :"foo.v2"=>"hoge"}
{:"foo.v1"=>"2", :"foo.v2"=>"fuga"}
以上で、rubyからhiveserver2へクエリを投げることが出来ました。