首页 > 解决方案 > Scala:按时间戳排序的数据帧中的 monotonically_increasing_id()

问题描述

这类似于一个较旧问题的设置,除了这次我有一个带有时间戳的时间序列,这样时间戳就不会出现在超过 1 条记录中。所以假设我有一个非常简单的数据框time_series,其中包含一个时间戳和一个整数列;它看起来像这样:

timestamp  | measured_value
--------------------------
2019-06-30 | 1828
2019-07-01 | 948
2019-07-02 | 2912
2019-07-03 | 2100
[etc.]

使用以下内容,我想添加一个单调递增的 id 并使用它:

time_series.createorReplaceView("tmp")
var sql_cmd = """select 
                    monotonically_increasing_id() as counter
                    , * 
                 from 
                    tmp
                 order by
                    timestamp asc""";
var new_time_series = spark.sql(sql_command);

Sonew_time_series具有与 相同数量的记录times_series,理想情况下看起来像这样:

counter | timestamp  | measured_value
-------------------------------------
0       | 2019-06-30 | 1828
1       | 2019-07-01 | 948
2       | 2019-07-02 | 2912
3       | 2019-07-03 | 2100
[etc.]

问题。是否counter保留由 给出的顺序timestamp,或者在数学上,如果给定 中的两个元素counter,n_1 和 n_2,那么当且仅当 n_1 旁边的时间戳小于 n_2 旁边的时间戳时,n_1 < n_2 是真的吗?

标签: sqlscalaapache-spark

解决方案


推荐阅读