Database Reference
In-Depth Information
The counter column (cell)
A counter column is a special purpose cell to keep count. A client application can incre-
ment or decrement it by an integer value. Counter columns cannot be mixed with regular or
any other cell types (as of Cassandra v2.0.9). So, a counter column always lives in a table
that has all the cells of type counter. Let's call this type of table a counter table. When we
have to use a counter, we either plug it into an existing counter table or create a separate
table with columns (CQL3 columns) as the counter type.
Counters require tight consistency, and this makes it a little complex for Cassandra. Under
the hood, Cassandra tracks distributed counters and uses system-generated timestamps. So
clock synchronization is crucial.
The counter tables behave a little differently than the regular ones. Cassandra makes a read
once in the background when a write for a counter column occurs. So it reads the counter
value before updating, which ensures that all the replicas are consistent. Since we know
this little secret, we can leverage this property while writing since the data is always con-
sistent. While writing to a counter column, we can use a consistency level of ONE . We
know from Chapter 2 , Cassandra Architecture , in the Replication topic that the lower the
consistency level, the faster the read/write operation. The counter writes can be very fast
without risking a false read.
Note
Clock synchronization can easily be achieved with NTPD ( http://www.ntp.org ). In general,
it's a good idea to keep your servers in sync.
Here's an example of a table with counter columns in it and the way to update it:
cqlsh:mastering_cassandra> CREATE TABLE demo_counter_cols
(city_name varchar PRIMARY KEY, count_users counter,
count_page_views counter);
cqlsh:mastering_cassandra> UPDATE demo_counter_cols SET
count_users = count_users + 1, count_page_views =
count_page_views + 42 WHERE city_name = 'newyork';
cqlsh:mastering_cassandra> UPDATE demo_counter_cols SET
count_users = count_users + 13 WHERE city_name =
Search WWH ::




Custom Search