微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Clickhouse 按顺序时间和特定类型查找事件对

如何解决Clickhouse 按顺序时间和特定类型查找事件对

我在 clickhouse 有 events 表。 当某个用户(由 user_id 定义)进入房间(由 object_id 定义)或离开房间时,应该打开由钥匙卡打开的电子锁,因此对于与锁的每次交互,events 表中都有一个记录相应的 event_type 设置为“来”或“左”。

CREATE TABLE default.events
(
 `user_id` UInt32,-- user of event
 `object_id` UInt32,-- object of event
 `event_type` String,-- type of event,can be "came" or "left"
 `event_moment_date` Date,-- date of event
 `event_moment` DateTime   -- datetime of event 
)
ENGINE = MergeTree(
    event_moment_date,(
        object_id,user_id,event_moment
    ),8192)

我需要以表格形式输出数据:

user_id,-- user 
object_id,-- object
came_moment,-- moment then user entered the room
left_moment  -- moment then user leaved the room

因此,对于每个“来”事件,我需要找到匹配的“左”事件,该事件具有相等的 user_id 和 object_id,并且在相对于“来” event_moment 的最近可能的将来具有 event_datetime。

我可以在 MysqL/Postgrsql 中使用这样的子查询轻松做到这一点:

SELECT
    s1.object_id,s1.user_id,s1.action_moment as "came_moment",(
        select s2.action_moment from source as s2 
        where 
            s1.user_id = s2.user_id 
        and 
            s1.object_id = s2.object_id
        and 
            s1.action_moment < s2.action_moment
        and
            s2.action_type = 'left'
        order by s2.action_moment asc
        limit 1
    ) as "left_moment"
FROM
source as s1
where s1.action_type = 'came'

但 Clickhouse 不允许在子查询(依赖子查询)中使用外部查询字段

我也尝试过使用 JOIN,但 Clickhouse 不允许在 JOIN 的 ON 语句中使用“”。此外,我尝试使用 Clickhouse 的 neighbour 函数,按 event_moment 排序,但我通过对数据进行排序并选择,只选择了具有特定 came_moment 和相应 left_moment 的单行下一个邻居行,我似乎无法加载此类行的完整列表。

我开始认为我的任务在 ClickHouse 中是不可能的,我需要某种脚本(PHP/python/whatever)来扫描数据库添加一些“session_id”字段,每个字段都应该具有相同的 ID 号“来”和“左”对应的两行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。