如何区分cassandra里primary key,partition key,cluster key,clustering key

本文详细解析了数据库中主键的概念,包括简单的单字段主键和复合(复合)主键,并介绍了分区键和聚簇键的作用及如何进行查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此文来自 stackoverflow, 有时候自己也搞混, mark 一下:

There is a lot of confusion around this, I will try to make it as simple as possible.

The primary key is a general concept to indicate one or more columns used to retrieve data from a Table.

The primary key may be SIMPLE

 create table stackoverflow (
      key text PRIMARY KEY,
      data text      
  );

That means that it is made by a single column.

But the primary key can also be COMPOSITE (aka COMPOUND), generated from more columns.

 create table stackoverflow (
      key_part_one text,
      key_part_two int,
      data text,
      PRIMARY KEY(key_part_one, key_part_two)      
  );

In a situation of COMPOSITE primary key, the "first part" of the key is called PARTITION KEY (in this example key_part_one is the partition key) and the second part of the key is theCLUSTERING KEY (key_part_two)

Please note that the both partition and clustering key can be made by more columns

 create table stackoverflow (
      k_part_one text,
      k_part_two int,
      k_clust_one text,
      k_clust_two int,
      k_clust_three uuid,
      data text,
      PRIMARY KEY((k_part_one,k_part_two), k_clust_one, k_clust_two, k_clust_three)      
  );

Behind these names ...

  • The Partition Key is responsible for data distribution accross your nodes.  //partition key 在cassandra内部先转换为primary key 的hash, 根据hash 找到对应Node的token , 这样就直接来到了需要的nodes 节点上
  • The Clustering Key is responsible for data sorting within the partition.
  • The Primary Key is equivalent to the Partition Key in a single-field-key table.
  • The Composite/Compund Key is just a multiple-columns key

Further usage information: DATASTAX DOCUMENTATION


EDIT due to further requests
Small usage and content examples
SIMPLE  KEY:

insert into stackoverflow (key, data) VALUES ('han', 'solo');
select * from stackoverflow where key='han';

table content

key | data
----+------
han | solo

COMPOSITE/COMPOUND KEY can retrieve "wide rows"

insert into stackoverflow (key_part_one, key_part_two, data) VALUES ('ronaldo', 9, 'football player');
insert into stackoverflow (key_part_one, key_part_two, data) VALUES ('ronaldo', 10, 'ex-football player');
select * from stackoverflow where key_part_one = 'ronaldo';

table content

 key_part_one | key_part_two | data
--------------+--------------+--------------------
      ronaldo |            9 |    football player
      ronaldo |           10 | ex-football player

But you can query with all key ...

select * from stackoverflow where key_part_one = 'ronaldo' and key_part_two  = 10;

query output

 key_part_one | key_part_two | data
--------------+--------------+--------------------
      ronaldo |           10 | ex-football player

注意:上面select的例子是针对一下table: 

 create table stackoverflow (
      key_part_one text,
      key_part_two int,
      data text,
      PRIMARY KEY(key_part_one, key_part_two)      
  );
而不是: 

 create table stackoverflow (
      k_part_one text,
      k_part_two int,
      k_clust_one text,
      k_clust_two int,
      k_clust_three uuid,
      data text,
      PRIMARY KEY((k_part_one,k_part_two), k_clust_one, k_clust_two, k_clust_three)      
  );

Important note: the partition key is the minimum-specifier needed to perform a query using where clause. If you have a composite partition key, like the following: //特别注意: 当使用where时, primary key 是 cassandra 处理的最小单元。

eg: PRIMARY KEY((col1, col2), col10, col4))

You can perform query only passing at least both col1 and col2, these are the 2 columns that defines the partition key. The "general" rule to make query is you have to pass at least all partition key columns, then you can add each key in the order they're set.

so the valid queries are (excluding secondary indexes)

  • col1 and col2
  • col1 and col2 and col10
  • col1 and col2 and col10 and col 4

invalid:

  • col1 and col2 and col4
  • anything that does not contain both col1 and col2
<think>嗯,用户之前问过关于聊天记录存储和数据库选择的问题,现在他们想了解ClickHouse和Cassandra是什么。我需要先回顾之前的对话,确保回答的一致性和连贯性。之前我提到过在混合存储方案中使用ClickHouse进行分析,而Cassandra作为时序型数据库适用于海量数据。现在用户可能想更深入了解这两个数据库的特点和区别。 首先,用户可能是开发者或系统架构师,负责设计或优化系统架构。他们可能正在评估不同的数据库技术,用于处理大量数据,尤其是时间序列或分析型数据。用户的需求不仅仅是了解基本概念,而是需要知道两者的核心区别、适用场景以及如何选择。 接下来,我需要明确ClickHouse和Cassandra各自的定位。ClickHouse是OLAP数据库,擅长高速分析查询,适合处理大规模数据的聚合和报表生成。而Cassandra是宽列存储,强调高可用性和可扩展性,适合写密集型场景,比如实时数据写入和全局分布的数据存储。 用户可能想知道两者的架构差异、数据模型、性能特点以及适用场景。需要举例说明,比如在聊天记录存储中,Cassandra适合实时写入消息,而ClickHouse适合分析历史消息数据。同时,用户可能关心两者在分布式部署、一致性、事务支持等方面的区别。 还要注意用户可能存在的误区,比如将两者直接比较,而实际上它们的应用场景不同。需要强调选择时应根据具体需求,如数据写入量、查询模式、延迟要求等因素。 最后,确保回答结构清晰,分点说明,使用对比表格和示例帮助用户理解。结合之前的回答,提到混合存储方案中的ClickHouse和Cassandra的应用场景,加强用户的整体理解。</think>以下是ClickHouse与Cassandra的对比解析,结合具体技术特征和使用场景进行说明: --- ### 一、核心定位差异 ```mermaid graph LR A[数据处理类型] --> B[ClickHouse: OLAP分析] A --> C[Cassandra: OLTP+时序] D[设计目标] --> E["ClickHouse: 单表千亿级数据分析"] D --> F["Cassandra: 全球多数据中心写入"] ``` 1. **ClickHouse** - **核心价值**:在单台服务器上实现每秒GB级数据扫描 - **典型场景**:网站流量分析、广告投放效果统计、物联网设备历史数据分析 - **独特能力**:`GROUP BY`十亿级数据响应时间<1秒 2. **Cassandra** - **核心价值**:跨地域多活写入,无单点故障 - **典型场景**:物联网传感器数据采集、实时消息日志、用户行为轨迹记录 - **独特能力**:单个集群可支撑百万TPS写入 --- ### 二、架构设计对比 #### 数据分布模型 ```sql -- ClickHouse分片示例 CREATE TABLE logs ON CLUSTER 'analytics_cluster' ( timestamp DateTime, device_id UInt32, metric Float32 ) ENGINE = ReplicatedMergeTree() ORDER BY (toStartOfHour(timestamp), device_id) PARTITION BY toYYYYMMDD(timestamp); ``` ```cql -- Cassandra键空间定义 CREATE KEYSPACE sensor_data WITH replication = {'class': 'NetworkTopologyStrategy', 'DC1':3, 'DC2':2}; CREATE TABLE readings ( sensor_id uuid, bucket int, -- 按时间分桶 event_time timestamp, value decimal, PRIMARY KEY ((sensor_id, bucket), event_time) ) WITH CLUSTERING ORDER BY (event_time DESC); ``` **关键区别**: - ClickHouse:采用主从复制,适合星型拓扑 - Cassandra:无中心节点的P2P架构,所有节点平等 --- ### 三、性能特征对比 #### 基准测试数据(单集群) | 指标 | ClickHouse | Cassandra | |---------------------|---------------------|--------------------| | 写入速度 | 50-200 MB/s | 50K-500K ops/s | | 压缩率 | 5-10x (列式存储) | 1.5-3x (行式存储) | | 典型查询延迟 | 100ms-2s | 1-5ms (点查) | | 全表扫描速度 | 2-5 GB/s/节点 | 不推荐全表扫描 | | 最大单表记录数 | PB级 | TB级 | --- ### 四、使用场景对照 #### 1. 应选ClickHouse的场景 ```python # 电商用户行为分析查询 SELECT toStartOfDay(event_time) AS day, countDistinct(user_id) AS UV, sum(if(action_type='purchase',1,0)) AS orders FROM user_events WHERE event_date BETWEEN '2023-08-01' AND '2023-08-07' GROUP BY day HAVING UV > 1000 LIMIT 100 SETTINGS max_memory_usage=10000000000; -- 允许使用10GB内存 ``` **优势**:复杂聚合计算效率高,内存利用率优化好 #### 2. 应选Cassandra的场景 ```java // 物联网设备高频写入示例 public void writeSensorData(SensorRecord record) { PreparedStatement ps = session.prepare( "INSERT INTO sensor_readings (device_id, bucket, ts, value) VALUES (?, ?, ?, ?)"); BatchStatement batch = new BatchStatement(); for (DataPoint point : record.points) { int bucket = computeTimeBucket(point.timestamp); // 按小时分桶 batch.add(ps.bind(record.deviceId, bucket, point.timestamp, point.value)); } session.execute(batch); // 批量写入500个数据点 } ``` **优势**:高并发写入不丢数据,自动处理节点故障 --- ### 五、混合架构实践案例 **智能家居数据分析平台架构**: ```mermaid graph TD Devices[智能设备] -->|MQTT| Kafka Kafka --> Flink{实时处理} Flink -->|实时告警| Cassandra[(Cassandra 实时状态)] Flink -->|批量存储| ClickHouse[(ClickHouse 历史分析)] BI[报表系统] --> ClickHouse App[控制APP] --> Cassandra ``` **数据流向说明**: 1. 设备实时状态(如温度值)存入Cassandra,支持毫秒级查询 2. 历史运行数据每小时批量导入ClickHouse,生成能效报告 3. 业务系统从Cassandra获取最新状态,从ClickHouse获取趋势分析 --- ### 六、核心功能差异点 | 功能项 | ClickHouse | Cassandra | |---------------------|---------------------|--------------------| | 索引支持 | 跳数索引 | 二级索引(有限) | | 数据更新 | 异步批量更新 | 实时UPSERT | | 事务支持 | 不支持 | 轻量级事务 | | 地理分布 | 需外部分片方案 | 原生多数据中心 | | 机器学习集成 | SQL驱动ML | 需外接Spark | --- ### 七、运维关键指标对比 **ClickHouse集群扩容**: 1. 增加分片时需数据重分布 2. 典型扩容周期:存储使用达70%时 3. 备份方案:`clickhouse-backup`工具 **Cassandra集群扩容**: 1. 支持动态添加节点,数据自动均衡 2. 扩容触发点:单个节点磁盘>1TB时 3. 备份方案:`nodetool snapshot` --- **选择建议**: - 当需要分析100亿条记录生成聚合报表时,优先选择ClickHouse - 当需要全球20个数据中心同时写入时,必须使用Cassandra - 在实时监控场景中,可组合使用:Cassandra处理实时写入,ClickHouse进行T+1分析
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值