CassandraとHectorを試してみる。(1)

Cassandra(カサンドラ)は、apacheが提供するNoSQLといわれるタイプの分散データベースだ。NoSQLは、Not only SQLSQLだけではないぞ)という意味で、RDBが得意な分野にはRDBを使ってRDBが得意でない部分では他の適したミドルウェアを使うということだ。Cassandraは、もともとFacebookで開発され、その後にApacheに移されたものらしい。Cassandraは、Javaで書かれ、APIも公開されている。どうもそのAPIが、コネクションプーリングやモニタリングなどの機能が貧弱なのか、それを補うためにHector(ヘクタ)が提供されているという経緯のようだ。

(1) Cassandraのインストール

Cassandraは http://cassandra.apache.org/ からダウンロードできる。私はapache-cassandra-2.0.0-bin.tar.gz を持ってきて、C:\cassandra\apache-cassandra-2.0.0 に展開した。以下の環境変数を設定する。


set JAVA_HOME = C:\Java\jdk1.7.0
set CASSANDRA_HOME = C:\cassandra\apache-cassandra-2.0.0
set CASSANDRA_CONF = %CASSANDRA_HOME%\conf
set CASSANDRA_MAIN = org.apache.cassandra.service.CassandraDaemon
set path = %path%;%CASSANDRA_HOME%\bin
cassandraサーバを起動してみる。cmdからcassandraを実行すればよいはず。

> cassandra
Starting Cassandra Server
Error occurred during initialization of VM
Could not reserve enough space for object heap
ヒープ領域が確保できないと言われる。%CASSANDRA_HOME%\binにあるcassandra.batを開いて、Java VMのサイズらしきところを小さめに変更した。

set JAVA_OPTS=-ea^
-javaagent:"%CASSANDRA_HOME%\lib\jamm-0.2.5.jar"^
-Xms128M^ // was Xms1G
-Xmx512M^ // was Xmx1G
-XX:+HeapDumpOnOutOfMemoryError^
-XX:+UseParNewGC^
-XX:+UseConcMarkSweepGC^
-XX:+CMSParallelRemarkEnabled^
-XX:SurvivorRatio=8^
-XX:MaxTenuringThreshold=1^
-XX:CMSInitiatingOccupancyFraction=75^
-XX:+UseCMSInitiatingOccupancyOnly^
-Dcom.sun.management.jmxremote.port=7199^
-Dcom.sun.management.jmxremote.ssl=false^
-Dcom.sun.management.jmxremote.authenticate=false^
-Dlog4j.configuration=log4j-server.properties^
-Dlog4j.defaultInitOverride=true
再度実行すると、一応サービスが起動されたようだ。

> cassandra
Starting Cassandra Server
INFO 12:18:56,572 Logging initialized
INFO 12:18:56,673 32bit JVM detected. It is recommended to run Cassandra on a 64bit JVM for better performance.
INFO 12:18:56,676 JVM vendor/version: Java HotSpot(TM) Client VM/1.7.0
INFO 12:18:56,676 Heap size: 129761280/518979584
(snip)
INFO 12:19:12,373 Starting listening for CQL clients on localhost/127.0.0.1:9042...
INFO 12:19:12,472 Binding thrift service to localhost/127.0.0.1:9160
INFO 12:19:12,621 Using TFramedTransport with a max frame size of 15728640 bytes.
INFO 12:19:12,665 Using synchronous/threadpool thrift server on localhost : 9160
INFO 12:19:12,667 Listening for thrift clients...

(2) cassandraコンソールで動作確認

もう1つ別にcmdを開いて、cassandraのコンソール(cassandra-cli)を起動してみる。ユーザーなどは指定していないが[default@unknown]というプロンプトが表示される。どんなコマンドがあるのか。help;と入力してみる。セミコロンが必要。exit;やquit;で抜けられる。


> cassandla-cli
Starting Cassandra Client
Connected to: "Test Cluster" on 127.0.0.1/9160
Welcome to Cassandra CLI version 2.0.0

Please consider using the more convenient cqlsh instead of CLI
CQL3 is fully backwards compatible with Thrift data; see http://www.datastax.com/dev/blog/thrift-to-cql3

Type 'help;' or '?' for help.
Type 'quit;' or 'exit;' to quit.

[default@unknown] help;
Getting around:
? Display this help.
help; Display this help.
help ; Display command-specific help.
exit; Exit this utility.
quit; Exit this utility.

Commands:
assume Apply client side validation.
connect Connect to a Cassandra node.
consistencylevel Sets consisteny level for the client to use.
count Count columns or super columns.
create column family Add a column family to an existing keyspace.
create keyspace Add a keyspace to the cluster.
del Delete a column, super column or row.
decr Decrements a counter column.
describe cluster Describe the cluster configuration.
describe Describe a keyspace and its column families or column family in current keyspace.
drop column family Remove a column family and its data.
drop keyspace Remove a keyspace and its data.
drop index Remove an existing index from specific column.
get Get rows and columns.
incr Increments a counter column.
list List rows in a column family.
set Set columns.
show api version Show the server API version.
show cluster name Show the cluster name.
show keyspaces Show all keyspaces and their column families.
show schema Show a cli script to create keyspaces and column families.
truncate Drop the data in a column family.
update column family Update the settings for a column family.
update keyspace Update the settings for a keyspace.
use Switch to a keyspace.

[default@unknown]

column family, keyspace, clusterなどという概念があることは分かる。RDBとはちょっと違う感じだが、cluster=テーブルスペース, keyspace=データベース, column family=テーブルくらいの感覚でいいのだろう。row, column, super columnという概念もある。column familyの中にrow.column(=key)が定義でき、値(=value)が代入できる。そうかEXCELファイルをイメージすればいいのかな。EXCELのような2次元のテーブルでrow,column,cellを意識すれば分かりやすい。column family=ワークシート、keyspace=EXCELファイル、cluster=ファイルをまとめたフォルダやバインダといった感じかな。いくつかコマンドを手探りしてみる。

[default@unknown] show api version;
19.37.0
[default@unknown] show cluster name;
Test Cluster
[default@unknown] show keyspaces;

WARNING: CQL3 tables are intentionally omitted from 'show keyspaces' output.
See https://issues.apache.org/jira/browse/CASSANDRA-4377 for details.

Keyspace: system:
Replication Strategy: org.apache.cassandra.locator.LocalStrategy
Durable Writes: true
Options: []
Column Families:
ColumnFamily: IndexInfo
ColumnFamily: NodeIdInfo
ColumnFamily: hints
ColumnFamily: schema_keyspaces
Replication Strategy: org.apache.cassandra.locator.SimpleStrategy

Keyspace: system_traces:
Replication Strategy: org.apache.cassandra.locator.SimpleStrategy
Durable Writes: true
Options: [replication_factor:1]
Column Families:

[default@unknown] use system; // systemへ移動して
Authenticated to keyspace: system

[default@unknown] show schema; // 定義情報を参照
(snip)
[default@unknown] describe; // systemの詳細
(snip)
[default@unknown] describe IndexInfo; // system.IndexInfoの詳細
ColumnFamily: IndexInfo
"indexes that have been completed"
Key Validation Class: org.apache.cassandra.db.marshal.UTF8Type
Default column value validator: org.apache.cassandra.db.marshal.BytesType
Cells sorted by: org.apache.cassandra.db.marshal.UTF8Type
GC grace seconds: 0
Compaction min/max thresholds: 4/32
Read repair chance: 0.0
DC Local Read repair chance: 0.0
Populate IO Cache on flush: false
Replicate on write: true
Caching: KEYS_ONLY
Default time to live: 0
Bloom Filter FP chance: 0.01
Index interval: 128
Speculative Retry: NONE
Built indexes: []
Compaction Strategy: org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy
Compression Options:
sstable_compression: org.apache.cassandra.io.compress.LZ4Compressor

デフォルトで「Test Cluster」というclusterが利用できるようだ。明示的にconnectしなくても、cassandra-cliで起動すると、デフォルトでTest Clusterに接続される。Connected to: "Test Cluster" on 127.0.0.1/9160のメッセージが出ている。Test Clusterには、systemとsystem_tracesという2つのkeyspaceが作成されている。keyspaceは、database相当の概念だ。clusterはkeyspaceの集合を扱うので、Oracleなどのtablespace相当と捉えておくことにする。keyspaceはuseコマンドで移動できる。systemというkeyspaceには、IndexInfo, NodeIdInfo, hints, schema_keyspacesという4つのColumnFamilyがある。これらはtable相当だろう。
たとえば、systemというkeyspaceに移動して、IndexInfoというColumnFamilyの定義を覗いてみる。describe IndexInfoの結果をみると、IndexInfoはコンパイルされたインデックスの格納場所のようだ。カラムには例えば、Default time to liveといった長めの名前のものがあり、初期値=0 が設定されていることが分かる。

(3) set/get/delコマンド

set/get/delのコマンドを試してみたい。systemのkeyspaceを触わると問題があるかもしれないが、とりあえずsystemのIndexInfoを直接触ってみる。'test'というrowでアクセスしてみる。


> get IndexInfo['test']; // 'test'は存在していない。
Returned 0 results. // エラーにはならず、0件となる。
Elapsed time: 84 msec(s).

> set IndexInfo['test']['Default time to live'] = 23; // 整数の代入
Value inserted.
Elapsed time: 388 msec(s).

> set IndexInfo['test']['Replicate on write'] = 02; // 16進数(hex bytes)の代入
Value inserted.
Elapsed time: 114 msec(s).

> get IndexInfo['test']; // 'test'を取得
=> (name=Default time to live, value=23, timestamp=1379918657809000)
=> (name=Replicate on write, value=02, timestamp=1379918591765000)
Returned 2 results.

> del IndexInfo['test']; // 'test'を削除
row removed.
Elapsed time: 63 msec(s).

> get IndexInfo['test']; // 削除後に'test'を再取得
Returned 0 results.
Elapsed time: 84 msec(s).

今日はcassandraをコンソールで確認するまでしかできず、タイトルのScalaにもHectorにも辿りつけなった。(つづく)