NoSql 之 Cassandra 查询

[b]java操作Cassandra之前得操作一下步骤:[/b]
1.启动cassandra.
2.进入到${cassandra-home}\bin下,执行
cassandra-cli -host localhost -port 9160

3.创建空间:
create keyspace wingware;

4.切换到创建好的空间中:
use wingware;

5.创建column family:
create column family wing;

运行以下代码需要${cassandra-home}\lib下的*.jar添加到当前的classpath下.
SampleOne.java

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class SampleOne {
static Cassandra.Client cassandraClient;
static TTransport socket;

private static void init(String keySpace) throws InvalidRequestException, TException {
String server = "localhost";
int port = 9160;
/* 首先指定cassandra server的地址 */
socket = new TSocket(server, port);
System.out.println(" connected to " + server + ":" + port + ".");
TFramedTransport transport = new TFramedTransport(socket);
/* 指定通信协议为二进制流协议 */
TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport);
cassandraClient = new Cassandra.Client(binaryProtocol);
/* 建立通信连接 */
socket.open();
cassandraClient.set_keyspace(keySpace);
}

public static void main(String[] args) throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException {
/* 选择需要操作的Keyspaces, 可以理解成数据库的表 */
String keyspace = "wingware";

/* 初始化连接 */
init(keyspace);

/* 创建一个Table Name */
String columnFamily = "wing";

String tablename = "tablename";

/* 插入一条记录 */
insertOrUpdate(columnFamily, tablename, "xiexie2", "dddddddd", System.currentTimeMillis());
/* 删除一条记录 */
// delete(keyspace,tableName,row,"name",System.currentTimeMillis());
/* 获取一条记录 (由于插入和删除是同一条记录,有可能会检索不到哦!请大家主意! */
Column column = getByColumn(columnFamily, tablename, "key", System.currentTimeMillis());

System.out.println("read column " + columnFamily);
System.out.println("column name " + ":" + new String(column.getName()));
System.out.println("column value" + ":" + new String(column.getValue()));
System.out.println("column timestamp" + ":" + (column.timestamp));
column = getByColumn(columnFamily, tablename, "xiexie", System.currentTimeMillis());

System.out.println("read row " + columnFamily);
System.out.println("column name " + ":" + new String(column.getName()));
System.out.println("column value" + ":" + new String(column.getValue()));
System.out.println("column timestamp" + ":" + (column.timestamp));
close();
}

/**
* 插入记录
*/
public static void insertOrUpdate(String columnFamily, String tableName, String ColumnName, String ColumnValue, long timeStamp) throws TException, TimedOutException, InvalidRequestException,
UnavailableException, NotFoundException {
/* 数据所在的行标 */

/* 创建一个column path */
ColumnParent parent = new ColumnParent(columnFamily);
Column col = new Column();
col.setName(ColumnName.getBytes());
col.setValue(ColumnValue.getBytes());

/*
* 执行插入操作,指定keysapce, row, col, 和数据内容, 后面两个参数一个是timestamp,
* 另外一个是consistency_level timestamp是用来做数据一致性保证的,
* 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo
*/
cassandraClient.insert(Translater.toByteBuffer(tableName), parent, col, ConsistencyLevel.ONE);
}

/**
* 删除记录
*/
public static void delete(String columnFamily, String tablename, String ColumnName, long timeStamp) throws TException, TimedOutException, InvalidRequestException, UnavailableException,
NotFoundException {
/* 选择需要操作的Keyspaces, 存放数据表所在的空间位置 */
/* 数据所在的行标 */
/* 创建一个column path */
ColumnPath col = new ColumnPath(columnFamily);
col.setColumn(ColumnName.getBytes());

/*
* 执行删除操作,指定keysapce, row, col, 后面两个参数一个是timestamp,
* 另外一个是consistency_level timestamp是用来做数据一致性保证的,
* 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo
*/
cassandraClient.remove(Translater.toByteBuffer(tablename), col, System.currentTimeMillis(), ConsistencyLevel.ONE);
}

/**
* 获取数据
*/
public static Column getByColumn(String columnFamily, String tablename, String ColumnName, long timeStamp) throws TException, TimedOutException, InvalidRequestException, UnavailableException,
NotFoundException {

/* 创建一个columnFamily */
ColumnPath col = new ColumnPath(columnFamily);
col.setColumn(ColumnName.getBytes());
/*
* 执行查询操作,指定keysapce, row, col, timestamp timestamp是用来做数据一致性保证的,
* 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo
*/
ColumnOrSuperColumn superColumn = cassandraClient.get(Translater.toByteBuffer(tablename), col, ConsistencyLevel.ONE);
System.out.println(">>>>>>>>>>>>>>>>"+superColumn);

Column column = cassandraClient.get(Translater.toByteBuffer(tablename), col, ConsistencyLevel.ONE).column;
return column;
}

/**
* 关闭当前的远程访问连接
*/
public static void close() {
socket.close();
}
}



Translater.java


import java.nio.ByteBuffer;  
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class Translater {

public static Charset charset = Charset.forName("UTF-8");
public static CharsetEncoder encoder = charset.newEncoder();
public static CharsetDecoder decoder = charset.newDecoder();

public static ByteBuffer toByteBuffer(String msg) {
try {
return encoder.encode(CharBuffer.wrap(msg));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static String toString(ByteBuffer buffer) {
String data = "";
try {
int old_position = buffer.position();
data = decoder.decode(buffer).toString();
// reset buffer's position to its original so it is not altered:
buffer.position(old_position);
} catch (Exception e) {
e.printStackTrace();
return "";
}
return data;
}
}


keyspace+columnFamily+tablename+column;
若column不存在,会抛出,而不是返回null.
Exception in thread "main" NotFoundException()
at org.apache.cassandra.thrift.Cassandra$get_result.read(Cassandra.java:5932)
at org.apache.cassandra.thrift.Cassandra$Client.recv_get(Cassandra.java:489)
at org.apache.cassandra.thrift.Cassandra$Client.get(Cassandra.java:462)


[b]cassandra的命令:[/b]

List of all CLI commands:
? Display this message.
help; Display this help.
help <command>; Display detailed, command-specific help.
connect <hostname>/<port> (<username> '<password>')?; Connect to thrift service.
use <keyspace> [<username> 'password']; Switch to a keyspace.
describe keyspace (<keyspacename>)?; Describe keyspace.
exit; Exit CLI.
quit; Exit CLI.
describe cluster; Display information about cluster.
show cluster name; Display cluster name.
show keyspaces; Show list of keyspaces.
show api version; Show server API version.
create keyspace <keyspace> [with <att1>=<value1> [and <att2>=<value2> ...]];
Add a new keyspace with the specified attribute(s) and value(s).
update keyspace <keyspace> [with <att1>=<value1> [and <att2>=<value2> ...]];
Update a keyspace with the specified attribute(s) and value(s).
create column family <cf> [with <att1>=<value1> [and <att2>=<value2> ...]];
Create a new column family with the specified attribute(s) and value(s).
update column family <cf> [with <att1>=<value1> [and <att2>=<value2> ...]];
Update a column family with the specified attribute(s) and value(s).
drop keyspace <keyspace>; Delete a keyspace.
drop column family <cf>; Delete a column family.
get <cf>['<key>']; Get a slice of columns.
get <cf>['<key>']['<super>']; Get a slice of sub columns.
get <cf> where <column> = <value> [and <column> > <value> and ...] [limit int];
get <cf>['<key>']['<col>'] (as <type>)*; Get a column value.
get <cf>['<key>']['<super>']['<col>'] (as <type>)*; Get a sub column value.
set <cf>['<key>']['<col>'] = <value> (with ttl = <secs>)*; Set a column.
set <cf>['<key>']['<super>']['<col>'] = <value> (with ttl = <secs>)*;
Set a sub column.
del <cf>['<key>']; Delete record.
del <cf>['<key>']['<col>']; Delete column.
del <cf>['<key>']['<super>']['<col>']; Delete sub column.
count <cf>['<key>']; Count columns in record.
count <cf>['<key>']['<super>']; Count columns in a super column.
truncate <column_family>; Truncate specified column family.
assume <column_family> <attribute> as <type>;
Assume a given column family attributes to match a specified type.
consistencylevel as <level>;
Change the consistency level for set,get, and list operations.
list <cf>; List all rows in the column family.
list <cf>[<startKey>:];
List rows in the column family beginning with <startKey>.
list <cf>[<startKey>:<endKey>];
List rows in the column family in the range from <startKey> to <endKey>.
list ... limit N; Limit the list results to N.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cassandra是一个混合型的非关系的数据库,类似于Google的BigTable。其主要功能比Dynomite(分布式的Key-Value存储系统)更丰富,但支持度却不如文档存储MongoDB(介于关系数据库和非关系数据库之间的开源产品,是非关系数据库当中功能最丰富,最像关系数据库的。支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型。)Cassandra最初由Facebook开发,后转变成了开源项目。它是一个网络社交云计算方面理想的数据库。以Amazon专有的完全分布式的Dynamo为基础,结合了Google BigTable基于列族(Column Family)的数据模型。P2P去中心化的存储。很多方面都可以称之为Dynamo 2.0。 功能   Cassandra的主要特点就是它不是一个数据库,而是由一堆数据库节点共同构成的一个分布式网络服务,对Cassandra 的一个写操作,会被复制到其他节点上去,对Cassandra的读操作,也会被路由到某个节点上面去读取。对于一个Cassandra群集来说,扩展性能是比较简单的事情,只管在群集里面添加节点就可以了。   这里有很多理由来选择Cassandra用于您的网站。和其他数据库比较,有三个突出特点: 模式灵活 :使用Cassandra,像文档存储,你不必提前解决记录中的字段。你可以在系统运行时随意的添加或移除字段。这是一个惊人的效率提升,特别是在大型部署上。 真正的可扩展性 :Cassandra是纯粹意义上的水平扩展。为给集群添加更多容量,可以指向另一台电脑。你不必重启任何进程,改变应用查询,或手动迁移任何数据。 多数据中心识别 :你可以调整你的节点布局来避免某一个数据中心起火,一个备用的数据中心将至少有每条记录的完全复制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值