Cassandra Query Language AKA CQL syntax


NOTE:  CQL V2 reference is available here http://crlog.info/2011/09/17/cassandra-query-language-cql-v2-0-reference/

A more recent version of the CQL Specification V1.0.0 is available here http://crlog.info/2011/06/13/cassandra-query-language-cql-v1-0-0-updated/

A very nice break down of the up and coming CQL syntax was posted on the Cassandra dev list yesterday.
It breaks down the current state of the query language in easy to understand steps. I’ve copied it purely for the sake
of duplication and getting it out there as much as possible. While CQL is still very immature it is gaining momentum
and is likely to become the de-facto interface to Cassandra.

The document’s contents are directly copied and pasted over from https://svn.apache.org/viewvc/cassandra/trunk/doc/cql/CQL.html?view=co :

Cassandra Query Language (CQL) v1.0.0

Table of Contents

  1. Cassandra Query Language (CQL) v1.0.0
    1. Table of Contents
    2. USE
    3. SELECT
      1. Specifying Columns
      2. Column Family
      3. Consistency Level
      4. Filtering rows
      5. Limits
    4. UPDATE
      1. Column Family
      2. Consistency Level
      3. Specifying Columns and Row
    5. DELETE
      1. Specifying Columns
      2. Column Family
      3. Consistency Level
      4. Specifying Rows
    6. TRUNCATE
    7. CREATE KEYSPACE
    8. CREATE COLUMNFAMILY
      1. Specifying Column Type (optional)
      2. Column Family Options (optional)
    9. CREATE INDEX
    10. DROP
    11. Common Idioms
      1. Specifying Consistency
      2. Term specification
  2. Versioning
  3. Changes

USE

Synopsis:

USE <KEYSPACE>; 

USE statement consists of the USE keyword, followed by a valid keyspace name. Its purpose is to assign the per-connection, current working keyspace. All subsequent keyspace-specific actions will be performed in the context of the supplied value.

SELECT

Synopsis:

SELECT [FIRST N] [REVERSED] <SELECT EXPR> FROM <COLUMN FAMILY> [USING <CONSISTENCY>] [WHERE <CLAUSE>] [LIMIT N]; 

SELECT is used to read one or more records from a Cassandra column family. It returns a result-set of rows, where each row consists of a key and a collection of columns corresponding to the query.

Specifying Columns

SELECT [FIRST N] [REVERSED] name1, name2, name3 FROM ... SELECT [FIRST N] [REVERSED] name1..nameN FROM ... 

The SELECT expression determines which columns will appear in the results and takes the form of either a comma separated list of names, or a range. The range notation consists of a start and end column name separated by two periods (..). The set of columns returned for a range is start and end inclusive.

The FIRST option accepts an integer argument and can be used to apply a limit to the number of columns returned per row. When this limit is left unset it defaults to 10,000 columns.

The REVERSED option causes the sort order of the results to be reversed.

It is worth noting that unlike the projection in a SQL SELECT, there is no guarantee that the results will contain all of the columns specified. This is because Cassandra is schema-less and there are no guarantees that a given column exists.

Column Family

SELECT ... FROM <COLUMN FAMILY> ... 

The FROM clause is used to specify the Cassandra column family applicable to a SELECT query.

Consistency Level

SELECT ... [USING <CONSISTENCY>] ... 

Following the column family clause is an optional consistency level specification.

Filtering rows

SELECT ... WHERE KEY = keyname AND name1 = value1 SELECT ... WHERE KEY >= startkey and KEY =< endkey AND name1 = value1 

The WHERE clause provides for filtering the rows that appear in results. The clause can filter on a key name, or range of keys, and in the case of indexed columns, on column values. Key filters are specified using the KEYkeyword, a relational operator, (one of =>>=<, and <=), and a term value. When terms appear on both sides of a relational operator it is assumed the filter applies to an indexed column. With column index filters, the term on the left of the operator is the name, the term on the right is the value to filter on.

Note: The greater-than and less-than operators (> and <) result in key ranges that are inclusive of the terms. There is no supported notion of “strictly” greater-than or less-than; these operators are merely supported as aliases to >= and <=.

Limits

SELECT ... WHERE <CLAUSE> [LIMIT N] ... 

Limiting the number of rows returned can be achieved by adding the LIMIT option to a SELECT expression. LIMIT defaults to 10,000 when left unset.

UPDATE

Synopsis:

UPDATE [USING CONSISTENCY ] SET name1 = value1, name2 = value2 WHERE KEY = keyname; 

An UPDATE is used to write one or more columns to a record in a Cassandra column family. No results are returned.

Column Family

UPDATE <COLUMN FAMILY> ... 

Statements begin with the UPDATE keyword followed by a Cassandra column family name.

Consistency Level

UPDATE ... [USING <CONSISTENCY>] ... 

Following the column family identifier is an optional consistency level specification.

Specifying Columns and Row

UPDATE ... SET name1 = value1, name2 = value2 WHERE KEY = keyname; 

Rows are created or updated by supplying column names and values in term assignment format. Multiple columns can be set by separating the name/value pairs using commas. Each update statement requires exactly one key to be specified using a WHERE clause and the KEY keyword.

Additionally, it is also possible to send multiple UPDATES to a node at once using a batch syntax:

BEGIN BATCH [USING ] UPDATE CF1 SET name1 = value1, name2 = value2 WHERE KEY = keyname1; UPDATE CF1 SET name3 = value3 WHERE KEY = keyname2; UPDATE CF2 SET name4 = value4, name5 = value5 WHERE KEY = keyname3; APPLY BATCH 

When batching UPDATEs, a single consistency level is used for the entire batch, it appears after the BEGIN BATCH statement, and uses the standard consistency level specification. Batch UPDATEs default toCONSISTENCY.ONE when left unspecified.

NOTE: While there are no isolation guarantees, UPDATE queries are atomic within a give record.

DELETE

Synopsis:

DELETE [COLUMNS] FROM [USING ] WHERE KEY = keyname1 DELETE [COLUMNS] FROM [USING ] WHERE KEY IN (keyname1, keyname2); 

DELETE is used to perform the removal of one or more columns from one or more rows.

Specifying Columns

DELETE [COLUMNS] ... 

Following the DELETE keyword is an optional comma-delimited list of column name terms. When no column names are specified, the remove applies to the entire row(s) matched by the WHERE clause

Column Family

DELETE ... FROM <COLUMN FAMILY> ... 

The column family name follows the list of column names.

Consistency Level

UPDATE ... [USING <CONSISTENCY>] ... 

Following the column family identifier is an optional consistency level specification.

Specifying Rows

UPDATE ... WHERE KEY = keyname1 UPDATE ... WHERE KEY IN (keyname1, keyname2) 

The WHERE clause is used to determine which row(s) a DELETE applies to. The first form allows the specification of a single keyname using the KEY keyword and the = operator. The second form allows a list of keyname terms to be specified using the IN notation and a parenthesized list of comma-delimited keyname terms.

TRUNCATE

Synopsis:

TRUNCATE <COLUMN FAMILY> 

Accepts a single argument for the column family name, and permanently removes all data from said column family.

CREATE KEYSPACE

Synopsis:

CREATE KEYSPACE WITH replication_factor = AND strategy_class = [AND strategy_options. = [AND strategy_options. = ]]; 

The CREATE KEYSPACE statement creates a new top-level namespace (aka “keyspace”). Valid names are any string constructed of alphanumeric characters and underscores, but must begin with a letter. Properties such as replication strategy and count are specified during creation using the following accepted keyword arguments:

keyword required description
replication_factor yes Numeric argument that specifies the number of replicas for this keyspace.
strategy_class yes Class name to use for managing replica placement. Any of the shipped strategies can be used by specifying the class name relative to org.apache.cassandra.locator, others will need to be fully-qualified and located on the classpath.
strategy_options no Some strategies require additional arguments which can be supplied by appending the option name to the strategy_options keyword, separated by a colon (:). For example, a strategy option of “DC1″ with a value of “1” would be specified as strategy_options:DC1 = 1.

CREATE COLUMNFAMILY

Synopsis:

CREATE COLUMNFAMILY [(name1 type, name2 type, ...)] [WITH keyword1 = arg1 [AND keyword2 = arg2 [AND ...]]]; 

CREATE COLUMNFAMILY statements create new column family namespaces under the current keyspace. Valid column family names are strings of alphanumeric characters and underscores, which begin with a letter.

Specifying Column Type (optional)

CREATE COLUMNFAMILY (name1 type, name2 type) ...; 

It is possible to assign columns a type during column family creation. Columns configured with a type are validated accordingly when a write occurs. Column types are specified as a parenthesized, comma-separated list of column term and type pairs. The list of recognized types are:

type description
bytes Arbitrary bytes (no validation)
ascii ASCII character string
utf8 UTF8 encoded string
timeuuid Type 1 UUID
uuid Type 4 UUID
int 4-byte integer
long 8-byte long

Note: In addition to the recognized types listed above, it is also possible to supply a string containing the name of a class (a sub-class of AbstractType), either fully qualified, or relative to theorg.apache.cassandra.db.marshal package.

Column Family Options (optional)

CREATE COLUMNFAMILY ... WITH keyword1 = arg1 AND keyword2 = arg2; 

A number of optional keyword arguments can be supplied to control the configuration of a new column family.

keyword default description
comparator utf8 Determines sorting and validation of column names. Valid values are identical to the types listed in Specifying Column Type above.
comment none A free-form, human-readable comment.
row_cache_size 0 Number of rows whose entire contents to cache in memory.
key_cache_size 200000 Number of keys per SSTable whose locations are kept in memory in “mostly LRU” order.
read_repair_chance 1.0 The probability with which read repairs should be invoked on non-quorum reads.
gc_grace_seconds 864000 Time to wait before garbage collecting tombstones (deletion markers).
default_validation utf8 Determines validation of column values. Valid values are identical to the types listed in Specifying Column Type above.
min_compaction_threshold 4 Minimum number of SSTables needed to start a minor compaction.
max_compaction_threshold 32 Maximum number of SSTables allowed before a minor compaction is forced.
row_cache_save_period_in_seconds 0 Number of seconds between saving row caches.
key_cache_save_period_in_seconds 14400 Number of seconds between saving key caches.
memtable_flush_after_mins 60 Maximum time to leave a dirty table unflushed.
memtable_throughput_in_mb dynamic Maximum size of the memtable before it is flushed.
memtable_operations_in_millions dynamic Number of operations in millions before the memtable is flushed.
replicate_on_write false

CREATE INDEX

Synopsis:

CREATE INDEX [index_name] ON <column_family> (column_name); 

CREATE INDEX statement is used to create a new, automatic secondary index for the named column.

DROP

Synopsis:

DROP <KEYSPACE|COLUMNFAMILY> namespace; 

DROP statements result in the immediate, irreversible removal of keyspace and column family namespaces.

Common Idioms

Specifying Consistency

... USING <CONSISTENCY> ... 

Consistency level specifications are made up the keyword USING, followed by a consistency level identifier. Valid consistency levels are as follows:

  • CONSISTENCY ZERO
  • CONSISTENCY ONE (default)
  • CONSISTENCY QUORUM
  • CONSISTENCY ALL
  • CONSISTENCY DCQUORUM
  • CONSISTENCY DCQUORUMSYNC

Term specification

Terms are used in statements to specify things such as keyspaces, column families, indexes, column names and values, and keyword arguments. The rules governing term specification are as follows:

  • Any single quoted string literal (example: 'apple').
  • Unquoted alpha-numeric strings that begin with a letter (example: carrot).
  • Unquoted numeric literals (example: 100).
  • UUID strings in hyphen-delimited hex notation (example: 1438fc5c-4ff6-11e0-b97f-0026c650d722).

Terms which do not conform to these rules result in an exception.

How column name/value terms are interpreted is determined by the configured type.

type term
ascii Any string which can be decoded using ASCII charset
utf8 Any string which can be decoded using UTF8 charset
uuid Standard UUID string format (hyphen-delimited hex notation)
timeuuid Standard UUID string format (hyphen-delimited hex notation)
timeuuid The string now, to represent a type-1 (time-based) UUID with a date-time component based on the current time
timeuuid Numeric value representing milliseconds since epoch
timeuuid An iso8601 timestamp
long Numeric value capable of fitting in 8 bytes
int Numeric value of arbitrary size
bytes Hex-encoded strings (converted directly to the corresponding bytes)

Versioning

Versioning of the CQL language adheres to the Semantic Versioning guidelines. Versions take the form X.Y.Z where X, Y, and Z are integer values representing major, minor, and patch level respectively. There is no correlation between Cassandra release versions and the CQL language version.

version description
Patch The patch version is incremented when bugs are fixed.
Minor Minor version increments occur when new, but backward compatible, functionality is introduced.
Major The major version must be bumped when backward incompatible changes are introduced. This should rarely (if ever) occur.

Changes

Tue, 22 Mar 2011 18:10:28 -0700 - Eric Evans <eevans@rackspace.com>
 * Initial version, 1.0.0

18 Responses to Cassandra Query Language AKA CQL syntax

  1. Pingback: Cassandra London Meet up and my introduction to CQL talk « Courtney Robinson 's log

  2. Pingback: Релиз Apache БД Cassandra 0.8.0

  3. Pingback: Релиз Apache БД Cassandra 0.8.0 | AllUNIX.ru – Всероссийский портал о UNIX-системах

  4. Pingback: Cassandra Query Language (CQL) v1.0.0 (UPDATED) « Courtney Robinson 's log

  5. Pingback: CQL : Creating a simple keyspace « Courtney Robinson 's log

  6. Pingback: Cassandra Query Language (CQL) v2.0 reference « Courtney Robinson 's log

  7. Pingback: Новости компьютерного мира - Релиз БД Apache Cassandra 1.0

  8. Pingback: Релиз БД Apache Cassandra 1.0 | AllUNIX.ru – Всероссийский портал о UNIX-системах

  9. Ansar Rafique says:

    Do we have the facility to query the range value or use the wildcards or even query from date to end date in Cassandra Query Language. I didnt find this function anywhere please give me an example.

  10. pravat kumar dash says:

    how to execute this query and where i i have to run?

  11. Pingback: Представлена БД Apache Cassandra 1.2 | Интересное в сети

  12. Pingback: Представлена БД Apache Cassandra 1.2 | AllUNIX.ru — Всероссийский портал о UNIX-системах

  13. Pingback: Представлена БД Apache Cassandra 1.2 : Записки начинающего линуксоида

  14. Pingback: Представлена БД Apache Cassandra 1.2 « conon print

  15. Pingback: All Things of World

  16. mosaic says:

    Your blog won’t render correctly on my iphone – you may want to try and repair that

    • zcourts says:

      I’ll be migrating my blog soon, that’ll be fixed then

  17. Pingback: Релиз БД Apache Cassandra 2.0 с поддержкой триггеров и легковесных транзакций | AllUNIX.ru — Всероссийский портал о UNIX-системах

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,384 other followers

%d bloggers like this: