Edit:可以找到执行此操作的方法和风险的完整示例here
来自文档
生成单调递增 64 位整数的列。
生成的ID保证单调递增且唯一,但不连续。当前的实现将分区 ID 放在高 31 位中,将每个分区内的记录号放在低 33 位中。假设数据框的分区数少于10亿个,每个分区的记录数少于80亿条。
因此,它不像 RDB 中的自增 id,而是not合并可靠。
如果您需要像 RDB 中那样的自动增量行为并且您的数据是可排序的,那么您可以使用row_number
df.createOrReplaceTempView('df')
spark.sql('select row_number() over (order by "some_column") as num, * from df')
+---+-----------+
|num|some_column|
+---+-----------+
| 1| ....... |
| 2| ....... |
| 3| ..........|
+---+-----------+
如果您的数据不可排序并且您不介意使用 rdds 创建索引然后回退到数据帧,您可以使用rdd.zipWithIndex()
可以找到一个例子here
简而言之:
# since you have a dataframe, use the rdd interface to create indexes with zipWithIndex()
df = df.rdd.zipWithIndex()
# return back to dataframe
df = df.toDF()
df.show()
# your data | indexes
+---------------------+---+
| _1 | _2|
+-----------=---------+---+
|[data col1,data col2]| 0|
|[data col1,data col2]| 1|
|[data col1,data col2]| 2|
+---------------------+---+
之后您可能需要更多的转换才能使您的数据框达到您需要的效果。注意:这不是一个非常高性能的解决方案。
希望这可以帮助。祝你好运!
Edit:想一想,你可以结合monotonically_increasing_id
使用row_number
:
# create a monotonically increasing id
df = df.withColumn("idx", monotonically_increasing_id())
# then since the id is increasing but not consecutive, it means you can sort by it, so you can use the `row_number`
df.createOrReplaceTempView('df')
new_df = spark.sql('select row_number() over (order by "idx") as num, * from df')
但不确定性能。