pyspark.sql.functions.monotonically_increasing_id

pyspark.sql.functions.monotonically_increasing_id() → pyspark.sql.column.Column[source]

A column that generates monotonically increasing 64-bit integers.

The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive. The current implementation puts the partition ID in the upper 31 bits, and the record number within each partition in the lower 33 bits. The assumption is that the data frame has less than 1 billion partitions, and each partition has less than 8 billion records.

New in version 1.6.0.

Changed in version 3.4.0: Supports Spark Connect.

Returns
Column

last value of the group.

Notes

The function is non-deterministic because its result depends on partition IDs.

As an example, consider a DataFrame with two partitions, each with 3 records. This expression would return the following IDs: 0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594.

Examples

>>> from pyspark.sql import functions as sf
>>> spark.range(0, 10, 1, 2).select(sf.monotonically_increasing_id()).show()
+-----------------------------+
|monotonically_increasing_id()|
+-----------------------------+
|                            0|
|                            1|
|                            2|
|                            3|
|                            4|
|                   8589934592|
|                   8589934593|
|                   8589934594|
|                   8589934595|
|                   8589934596|
+-----------------------------+