逖靖寒的世界

每天进步一点点

导航

Cassandra查询语句:CQL(Cassandra Query Language)

和SQL(结构化查询语言)类似,Cassandra也即将在未来的发行版本中提供Cassandra查询语句(CQL)。

比如使用Keyspace名称为WebSiteKS,使用CQL表示为:

USE WebSiteKS;

查询Column Family为Standard1,Key为k的值:

SELECT FROM Standard1 WHERE KEY = "k";

更新Column Family为Standard1,Key为k,Column为c的值:

UPDATE Standard1 WITH ROW("k", COL("c", "hello!"));

更多的有关CQL的语法详细信息可以参考官方的文档:https://svn.apache.org/repos/asf/cassandra/trunk/doc/cql/CQL.html

抛开CQL的语法,深入到Cassandra的内部实现,其也无非是解析CQL的操作类型,然后将其转化为内部的操作接口进行调用。

USE语句实现逻辑:

case USE:
    clientState.setKeyspace((String)statement.statement);

这里将Keyspace进行了切换,和直接调用Thrift API的setKeyspace效果一致。

SELECT语句实现逻辑:

case SELECT:
    SelectStatement select = (SelectStatement)statement.statement;
    List<CqlRow> avroRows = new ArrayList<CqlRow>();
    avroResult.type = CqlResultType.ROWS;
    List<org.apache.cassandra.db.Row> rows = null;
    if (!select.getKeyPredicates().isRange())
        rows = multiSlice(keyspace, select);
    else
        rows = multiRangeSlice(keyspace, select);

这与调用Thrift API的mutiSlice或multiRangeSlice效果一致:

UPDATE语句实现逻辑:

case UPDATE:
    UpdateStatement update = (UpdateStatement)statement.statement;
    validateColumnFamily(keyspace, update.getColumnFamily());
    avroResult.type = CqlResultType.VOID;
    List<RowMutation> rowMutations = new ArrayList<RowMutation>();
    for (Row row : update.getRows())
    {
        validateKey(row.getKey().getByteBuffer());
        RowMutation rm = new RowMutation(keyspace, row.getKey().getByteBuffer());
        for (org.apache.cassandra.cql.Column col : row.getColumns())
        {
            rm.add(new QueryPath(update.getColumnFamily(), null, col.getName().getByteBuffer()),
                   col.getValue().getByteBuffer(),
                   System.currentTimeMillis());
        }
        rowMutations.add(rm);
    }
    try
    {
        StorageProxy.mutate(rowMutations, update.getConsistencyLevel());
    }
    catch (org.apache.cassandra.thrift.UnavailableException e)
    {
        throw new UnavailableException();
    }
    catch (TimeoutException e)
    {
        throw new TimedOutException();
    }

这与调用Thrift API的batch_mutate效果一致:

虽然现在CQL功能还很弱,但是又向前迈向了一大步。

更多关于Cassandra的文章:http://www.cnblogs.com/gpcuster/tag/Cassandra/

posted on 2010-11-01 22:13  逖靖寒  阅读(18304)  评论(3编辑  收藏  举报