Cassandra查詢語句CQL的小技巧
和SQL(結(jié)構(gòu)化查詢語言)類似,Cassandra也即將在未來的發(fā)行版本中提供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!"));
更多的有關(guān)CQL的語法詳細信息可以參考官方的文檔:https://svn.apache.org/repos/asf/cassandra/trunk/doc/cql/CQL.html
拋開CQL的語法,深入到Cassandra的內(nèi)部實現(xiàn),其也無非是解析CQL的操作類型,然后將其轉(zhuǎn)化為內(nèi)部的操作接口進行調(diào)用。
USE語句實現(xiàn)邏輯:
- case USE:
- clientState.setKeyspace((String)statement.statement);
這里將Keyspace進行了切換,和直接調(diào)用Thrift API的setKeyspace效果一致。
SELECT語句實現(xiàn)邏輯:
- 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);
這與調(diào)用Thrift API的mutiSlice或multiRangeSlice效果一致:
UPDATE語句實現(xiàn)邏輯:
- 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();
- }
這與調(diào)用Thrift API的batch_mutate效果一致:
雖然現(xiàn)在CQL功能還很弱,但是又向前邁向了一大步。
更多關(guān)于Cassandra的文章:http://www.cnblogs.com/gpcuster/tag/Cassandra/
原文鏈接:http://www.cnblogs.com/gpcuster/archive/2010/11/01/1866668.html
【編輯推薦】