`
wingware
  • 浏览: 144863 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

NoSql 之 Cassandra 查询

阅读更多
java操作Cassandra之前得操作一下步骤:
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)



cassandra的命令:

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 楼 zendly 2015-09-12  
mark一下

相关推荐

    Nosql - Cassandra 入门学习

    Cassandra是一款分布式NoSQL数据库系统,特别适合处理大量结构化和半结构化数据。它的设计灵感来源于Google的Bigtable,旨在提供高可用性、线性可扩展性和强一致性的数据存储解决方案。在互联网时代,随着大数据的...

    nosql cassandra学习教程

    很多方面都可以称之为Dynamo 2.0。 功能  Cassandra的主要特点就是它不是一个数据库,而是由一堆数据库节点共同构成的一个分布式网络服务,对Cassandra 的一个写操作,会被复制到其他节点上去,对Cassandra的读...

    NoSql Apache Cassandra 非关系型数据库

    为了简化查询操作,Cassandra 引入了 Cassandra Query Language(CQL),它的语法接近 SQL,使得开发者更容易上手。 总的来说,Apache Cassandra 是一个适合处理大规模数据的高性能分布式数据库,尤其适用于需要高...

    java NoSql Cassandra hector

    Java NoSQL Cassandra Hector详解 在当今大数据时代,非关系型数据库(NoSQL)因其灵活性、高可扩展性和高性能,越来越受到开发者的青睐。Cassandra,作为NoSQL数据库家族中的重要一员,尤其在大规模分布式存储系统...

    [NOSQL] Cassandra 数据库系统简单介绍.doc

    Apache Cassandra 是一种开源的分布式 NoSQL 数据库系统,设计用于处理大规模数据,具有高可用性、可扩展性和强一致性的特点。它最初由 Facebook 开发,借鉴了 Google BigTable 的数据模型和 Amazon Dynamo 的分布式...

    Cassandra nosql

    在设计之初,Cassandra即定位为满足以下关键需求: ### 为什么要选择Cassandra? 1. **海量数据处理能力**:Cassandra能够高效存储和管理大量数据,如消息副本、消息反向索引以及个性化用户数据,这些数据类型和...

    Cassandra查询分析器

    Cassandra 查询分析器是 Apache Cassandra 数据库系统中的核心组件之一,它在数据查询过程中起着至关重要的作用。Cassandra 是一个分布式、高性能、可扩展的NoSQL数据库,广泛用于处理大规模的数据存储和检索任务。...

    NoSQL数据库(如MongoDB,Cassandra):NoSQL数据库的查询语言-CQL.docx

    NoSQL数据库(如MongoDB,Cassandra):NoSQL数据库的查询语言-CQL.docx

    NoSQL数据库系统-Cassandra分布式结构化数据存储视频教程

    Cassandra是一套开源分布式NoSQL数据库系统。它最初由Facebook开发,用于储存收件箱等简单格式数据,集GoogleBigTable的数据模型与Amazon Dynamo的完全分布式的架构于一身Facebook于2008将 Cassandra 开源,此后,...

    NoSQL Web Development with Apache Cassandra(2015)

    Apache Cassandra is the most commonly used NoSQL database written in Java and is renowned in the industry as the only NoSQL solution that can accommodate the complex requirements of today’s modern ...

    Cassandra实战 java NoSql

    Cassandra实战 java NoSql

    NoSQL应用场景及Cassandra架构分析.pptx

    CAP理论是NoSQL数据库设计的核心理论之一,它指出在分布式系统中,一致性、可用性和分区容错性无法同时得到保证,需要根据实际需求在三者之间作出权衡。Cassandra选择了CP,强调一致性与分区容错,但在牺牲了一致性...

    NoSQL学习之路

    Cassandra 是一种基于分布式系统的 NoSQL 数据库,它可以存储大量的数据,并提供高性能的查询功能。Cassandra 的主要特点是,使用了基于列的存储结构,以提高查询性能。 PNUTS 是一种基于分布式系统的 NoSQL 数据库...

    数据源管理 分布式NoSQL系统,Cassandra集群管理.docx

    ### 数据源管理与分布式NoSQL系统——Cassandra集群管理 #### Cassandra简介 **1.1 基础描述** Cassandra是一款开源的分布式NoSQL数据库系统,最初由Facebook开发,旨在为诸如收件箱这样的简单格式数据提供高效的...

    NoSQL Manager for MongoDB

    可视化MongoDB数据库管理工具,NoSQL Manager for MongoDB,破解版,解压就可以用。

    NoSQL(SequoiaDB&Cassandra&MongoDB)Benchmark性能对比测试报告

    SequoiaDB、Cassandra和MongoDB都是流行的NoSQL数据库解决方案,它们各自在性能、架构和适用场景上有着不同的特点。SequoiaDB是一个分布式文档数据库,拥有水平可扩展、高可用性、强一致性和高性能等特性。Cassandra...

    NoSQL性能评估(MongoDB,HBase,Cassandra):哪种数据库最适合你的数据?

    非关系数据库(经常被称为NoSQL)的特点是弹性和可伸缩性。另外,它们可以存储大数据并与云计算系统协同工作。这些因素导致非关系数据库非常流行。在2013年,NoSQL数据库的种类达到了150多个,并且一直在增长,多种...

    NoSQL数据库(如MongoDB,Cassandra):NoSQL数据库概论与历史.docx

    NoSQL数据库(如MongoDB,Cassandra):NoSQL数据库概论与历史.docx

Global site tag (gtag.js) - Google Analytics