map_keys
Returns an unordered array containing the keys of the map.
Syntax
Python
from pyspark.sql import functions as sf
sf.map_keys(col)
Parameters
Parameter | Type | Description |
|---|---|---|
|
| Name of column or expression |
Returns
pyspark.sql.Column: Keys of the map as an array.
Examples
Example 1: Extracting keys from a simple map
Python
from pyspark.sql import functions as sf
df = spark.sql("SELECT map(1, 'a', 2, 'b') as data")
df.select(sf.sort_array(sf.map_keys("data"))).show()
Output
+--------------------------------+
|sort_array(map_keys(data), true)|
+--------------------------------+
| [1, 2]|
+--------------------------------+
Example 2: Extracting keys from a map with complex keys
Python
from pyspark.sql import functions as sf
df = spark.sql("SELECT map(array(1, 2), 'a', array(3, 4), 'b') as data")
df.select(sf.sort_array(sf.map_keys("data"))).show()
Output
+--------------------------------+
|sort_array(map_keys(data), true)|
+--------------------------------+
| [[1, 2], [3, 4]]|
+--------------------------------+
Example 3: Extracting keys from an empty map
Python
from pyspark.sql import functions as sf
df = spark.sql("SELECT map() as data")
df.select(sf.map_keys("data")).show()
Output
+--------------+
|map_keys(data)|
+--------------+
| []|
+--------------+