2011年9月30日金曜日

Hectorを使ったCassandraへのアクセス ~CQL~

CassandraへHectorを使用してアクセスを行う。
今回は、CQLを使ったアクセスを試みます。

package com.zomu.t;

import java.nio.charset.CharacterCodingException;

import me.prettyprint.cassandra.model.CqlQuery;
import me.prettyprint.cassandra.model.CqlRows;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.query.QueryResult;

/**
 * CQLアクセステスト
 * @author nozomu
 */
public class AccessTestCql {

	/** 文字列シリアライザ */
	private static StringSerializer stringSerializer = StringSerializer.get();

	/**
	 *
	 * @param args
	 * @throws CharacterCodingException
	 */
	public static void main(String[] args) throws CharacterCodingException {

		// クラスタ
		Cluster cluster = HFactory.getOrCreateCluster("TestCluster",
				"localhost:9160");
		// 使用するKeySpace
		Keyspace keyspaceOperator = HFactory.createKeyspace("Giraffe", cluster);

		try {

			// CQLクエリを発行するクラス
			CqlQuery<String, String, String> cqlQuery = new CqlQuery<String, String, String>(
					keyspaceOperator, stringSerializer, stringSerializer,
					stringSerializer);
			// CQLを設定
			cqlQuery.setQuery("select * from CF where key = 'key'");

			// 取得する
			QueryResult> result = cqlQuery
					.execute();

			if (result != null) {
				CqlRows rows = result.get();

				if (rows != null) {
					for (Row row : rows.getList()) {
						for (HColumn col : row.getColumnSlice()
								.getColumns()) {
							System.out.println(col.getName() + " : "
									+ col.getValue());
						}
					}
				}
			}
		} catch (HectorException he) {
			he.printStackTrace();
		}
		cluster.getConnectionManager().shutdown();
	}
}


CQLはこれからCassandraを使用する場合には必須となりそうな予感がする。
ObjectMapper等もHectorには用意してあるみたいなので、併せてこちらも試す事にしようと思う。
それはまた次回にでも。

0 件のコメント:

コメントを投稿