Cassandra 文件

版本

您正在檢視預發行版本的說明文件。

Cassandra 快速入門

步驟 1:使用 Docker 取得 Cassandra

您需要在電腦上安裝 Docker Desktop for Mac、Docker Desktop for Windows 或類似的軟體。

Apache Cassandra 也以 tarball 或套件 下載提供。

docker pull cassandra:latest

步驟 2:啟動 Cassandra

Docker 網路讓我們可以存取容器的埠,而不用在主機上公開這些埠。

docker network create cassandra

docker run --rm -d --name cassandra --hostname cassandra --network cassandra cassandra

步驟 3:建立檔案

Cassandra 查詢語言 (CQL) 與 SQL 非常類似,但適合 Cassandra 的無 JOIN 結構。

建立一個名為 data.cql 的檔案,並將以下 CQL 程式碼貼到其中。這個程式碼將建立一個鍵值空間(Cassandra 在其中複製其資料的層)、一個用於儲存資料的表格,並將一些資料插入該表格

CREATE KEYSPACE IF NOT EXISTS store WITH REPLICATION =
{ 'class' : 'SimpleStrategy',
'replication_factor' : '1'
};

CREATE TABLE IF NOT EXISTS store.shopping_cart (
    userid text PRIMARY KEY,
    item_count int,
    last_update_timestamp timestamp
);

INSERT INTO store.shopping_cart
    (userid, item_count, last_update_timestamp)
    VALUES ('9876', 2, toTimeStamp(now()));
INSERT INTO store.shopping_cart
    (userid, item_count, last_update_timestamp)
    VALUES ('1234', 5, toTimeStamp(now()));

步驟 4:使用 CQLSH 載入資料

CQL shell 或 cqlsh 是用於與資料庫互動的工具之一。我們將使用它來使用您剛剛儲存的程式碼載入一些資料到資料庫中。

docker run --rm --network cassandra \
-v "$(pwd)/data.cql:/scripts/data.cql" \
-e CQLSH_HOST=cassandra -e CQLSH_PORT=9042 \
-e CQLVERSION=3.4.6 nuvo/docker-cqlsh

cassandra 伺服器本身(您執行的第一個 docker run 指令)需要幾秒鐘才能啟動。如果伺服器尚未完成其初始化序列,上述指令將會傳回錯誤,因此請給它幾秒鐘的時間啟動。

步驟 5:互動式 CQLSH

就像 SQL shell 一樣,您當然也可以使用 cqlsh 互動式執行 CQL 指令。

docker run --rm -it --network \
cassandra nuvo/docker-cqlsh cqlsh cassandra \
9042 --cqlversion='3.4.5'

這應該會讓您看到一個提示,如下所示

Connected to Test Cluster at cassandra:9042.
[cqlsh 5.0.1 | Cassandra 4.0.4 | CQL spec 3.4.5 | Native protocol v5]
Use HELP for help.
cqlsh>

步驟 6:讀取一些資料

SELECT * FROM store.shopping_cart;

步驟 7:寫入更多資料

INSERT INTO store.shopping_cart
    (userid, item_count)
    VALUES ('4567', 20);

步驟 8:清除

docker kill cassandra
docker network rm cassandra

恭喜!

嘿,這一點都不難,對吧?

若要深入了解,我們建議您執行下列步驟

  • 閱讀 Cassandra 基礎知識 以了解主要概念以及 Cassandra 在高層級如何運作。

  • 瀏覽 案例研究 以了解我們全球社群中的其他使用者如何從 Cassandra 中獲得價值。