【问题标题】:Cassandra update previous rows after insertCassandra 在插入后更新前几行
【发布时间】:2019-08-12 06:46:58
【问题描述】:

我在 cassandra 中有这个架构:

create table if not exists 
converstation_events(
    timestamp timestamp, 
    sender_id bigint, 
    conversation_id bigint, 
    message_type varchar, 
    message text, 
    primary key ((conversation_id), sender_id, message_type, timestamp));

还有一个值为conversation_ended 的message_type,有没有办法对数据进行非规范化,以便我可以对那些已经结束的对话进行查询?

我考虑过有一个额外的字段,可以在会话结束消息到达系统时由触发器更新,这有意义吗?

【问题讨论】:

    标签: cassandra data-modeling cqlsh


    【解决方案1】:

    在 Cassandra 中,您需要以能够回答问题的方式对数据进行建模。它不像 RDBMS,您首先创建模型,然后创建查询。所以倒过来想想……

    当您在 cassandra 中进行查询时(大多数情况下......),您需要通过主键进行查询,并且可以使用集群键来过滤或选择范围。 great post 就可以了。

    您的converstation_events 表将为您提供有关对话的答案,按发件人、类型和时间进行过滤。 ** 如果要按时间过滤,则必须在查询中包含 sender_idmessage_type

    但是您想要给定类型的所有对话,因此您需要另一个表来回答此查询。如果您想要conversation_ended 的所有对话,您可以创建第二个表来将消息类型映射到对话,例如 -

    conversation_by_message_type (
        message_type varchar, 
        conversation_id bigint, 
        timestamp timestamp, 
        primary key ((message_type), timestamp, conversation_id));
    

    在客户端,只要您插入带有您可能想要查找的给定message_type 的convertation_events 事件,就必须向conversation_by_message_type 添加一条记录。我在此表中有timestamp,因此您可以按时间或timeconversation_id 进行排序或过滤。

    要查找所有已结束的对话,您可以执行以下查询

    <ids> = select conversation_id from conversation_by_message_type where message_type = 'conversation_ended'
    
    select * from conversation_events where conversation_id IN (<ids>)
    

    【讨论】:

    • 我需要的是能够查询对话结束的所有消息。 (就像一个版本:select * from messages where conversation_id in (select convertation_id where message_type = 'conversation_ended'); 因为你不能这样做,我 Cassandra,我想在更新的行中添加另一个字段插入了对话结束事件。像“is_ended”或类似的东西
    • 使用 cassandra,您需要首先定义您的查询(问题)并设计您的模型以便能够回答这些问题。主键的分区键部分控制您的数据所在的节点。你想远离集群扫描——这就是为什么第二个索引可能不是一个好主意。像上面那样使用第二张桌子(常见的事情......)可以让你做你想做的事。你只需要在客户端做这件事
    • 但我仍然有同样的问题。当该消息来自封闭的对话时,在客户端 idk 上。我应该在架构中添加一个字段'is_closed:并将它们插入到false,然后当conversation_close事件到达系统更新is_closed = true where conversation_id = conversation_id from closed事件?这有意义吗?我可以用触发器吗?
    • 不...这没有意义。听起来你试图让 cassandra 表现得像 MySql 一样。除了第二个索引之外,您无法真正过滤非关键字段。您需要一个“conversation_by_message_type”索引来查找给定类型的消息。我将扩大我的答案。..
    猜你喜欢
    • 2016-09-19
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多