使用計數器
計數器是專門用於儲存數字的欄位,該數字會透過遞增或遞減來更新。
若要將資料載入計數器欄位,或增加或減少計數器的值,請使用 UPDATE 指令。Apache Cassandra 會拒絕在指令中使用 USING TIMESTAMP 或 USING TTL 來更新計數器欄位。
程序
-
為計數器欄位建立表格。
CREATE TABLE IF NOT EXISTS cycling.popular_count ( id UUID PRIMARY KEY, popularity counter );
-
將資料載入計數器欄位的方式與其他表格不同。資料會更新,而不是插入。
BEGIN COUNTER BATCH UPDATE cycling.popular_count SET popularity = popularity + 1 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47; UPDATE cycling.popular_count SET popularity = popularity + 125 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47; UPDATE cycling.popular_count SET popularity = popularity - 64 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47; APPLY BATCH;
UPDATE cycling.popular_count SET popularity = popularity + 2 WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
-
popularity
欄位的值為 64。
其他遞增或遞減會變更計數器欄位的值。