使用配置单元脚本处理每个开始/结束对的时间跨度

cbwuti44  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(692)

我有一个可以启动或停止的服务。每个操作生成一个带有时间戳和操作类型的记录。最终,我得到了一系列带时间戳的操作记录。现在我要计算一天中服务的运行时间。想法很简单。对于每对开始/停止记录,计算时间跨度并求和。但我不知道如何实现它与Hive,如果可能的话。我可以创建表来存储中间结果。这是主要的阻塞问题,还有一些其他的小问题。例如,一些开始/停止对可能跨越一天。任何关于如何处理这个小问题的想法都将不胜感激。
样本数据:

  1. Timestamp Operation
  2. ... ...
  3. 2017-09-03 23:59:00 Start
  4. 2017-09-04 00:01:00 Stop
  5. 2017-09-04 06:50:00 Start
  6. 2017-09-04 07:00:00 Stop
  7. 2017-09-05 08:00:00 Start
  8. ... ...

服务结束时间 2017-09-04 那么应该是 1 + 10 = 11 分钟。请注意,第一个时间间隔跨越 09-03 以及 09-04 ,只有属于 09-04 被计算在内。

dxpyg8gm

dxpyg8gm1#

  1. select to_date(from_ts) as dt
  2. ,sum (to_unix_timestamp(to_ts) - to_unix_timestamp(from_ts)) / 60 as up_time_minutes
  3. from (select case when pe.i = 0 then from_ts else cast(date_add(to_date(from_ts),i) as timestamp) end as from_ts
  4. ,case when pe.i = datediff(to_ts,from_ts) then to_ts else cast(date_add(to_date(from_ts),i+1) as timestamp) end as to_ts
  5. from (select `operation`
  6. ,`Timestamp` as from_ts
  7. ,lead(`Timestamp`) over (order by `Timestamp`) as to_ts
  8. from t
  9. ) t
  10. lateral view posexplode(split(space(datediff(to_ts,from_ts)),' ')) pe as i,x
  11. where `operation` = 'Start'
  12. and to_ts is not null
  13. ) t
  14. group by to_date(from_ts)
  15. ;
  1. +------------+-----------------+
  2. | dt | up_time_minutes |
  3. +------------+-----------------+
  4. | 2017-09-03 | 1.0 |
  5. | 2017-09-04 | 11.0 |
  6. +------------+-----------------+
展开查看全部

相关问题