How to collect map keys in PySpark Azure Databricks?

Are you looking to find out how to collect keys from a MapType column of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to extract the MapType column unique keys into a python list of PySpark Databricks using the map_keys() function? If you are looking for any of these problem solutions, you have landed on the correct page. I will also help you how to use PySpark map_keys() function with multiple examples in Azure Databricks. I will explain it by taking a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to use the map_keys() function in PySpark.

In this blog, I will teach you the following with practical examples:

  • Syntax of map_keys() function
  • Getting the keys from a MapType column
  • Getting unique keys from a MapType column

The Pyspark map_keys() function is used to get an unordered array containing the keys of the map.

Syntax:

map_keys()

What is the syntax of the map_keys() function in PySpark Azure Databricks?

The syntax is as follows:

map_keys(*column)
Parameter NameRequiredDescription
column (str, Column)YesIt represents the keys extracting column name
Table 1: map_keys() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: map_keys()

Create a simple DataFrame

Let’s understand the use of the map_keys() function with various examples. Let’s start by creating a DataFrame.

Gentle reminder:

In Databricks,

  • sparkSession made available as spark
  • sparkContext made available as sc

In case, you want to create it manually, use the below code.

from pyspark.sql.session import SparkSession

spark = SparkSession.builder 
    .master("local[*]") 
    .appName("azurelib.com") 
    .getOrCreate()

sc = spark.sparkContext

a) Create manual PySpark DataFrame

data = [
    ("Arasan", ({"age": "23", "blood": "B+"})),
    ("Karthik", ({"age": "24", "blood": "B-"})),
    ("Sanjay", ({"age": "28", "blood": "O-", "state": "TN"})),
    ("Marish", None)
]

df = spark.createDataFrame(data, schema=["name", "info"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- name: string (nullable = true)
 |-- info: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)

+-------+-------------------------------------+
|name   |info                                 |
+-------+-------------------------------------+
|Arasan |{blood -> B+, age -> 23}             |
|Karthik|{blood -> B-, age -> 24}             |
|Sanjay |{state -> TN, blood -> O-, age -> 28}|
|Marish |null                                 |
+-------+-------------------------------------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_path with the source file location which you have downloaded.

df_2 = spark.read.format("json").load(file_path)
df_2.printSchema()

"""
root
 |-- name: string (nullable = true)
 |-- info: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)
"""

Note: Here, I will be using the manually created DataFrame.

How to get keys from a MapType column of PySpark DataFrame using Azure Databricks?

Let’s see how to get keys from a MapType column in PySpark using Azure Databricks using various methods.

Example:

from pyspark.sql.functions import map_keys

df.select(map_keys("info")).show()

"""
Output:

+-------------------+
|     map_keys(info)|
+-------------------+
|       [blood, age]|
|       [blood, age]|
|[state, blood, age]|
|               null|
+-------------------+

"""

As you can see the extracted keys from the map type column are unordered.

How to get unique keys from a MapType column of PySpark DataFrame using Azure Databricks?

Let’s see how to get unique keys from a MapType column into a python list in PySpark using Azure Databricks using various methods.

Example:

from pyspark.sql.functions import map_keys, explode

# 1. Unique keys
unique_keys_df = df \
.select(explode(map_keys("info")).alias("keys")).distinct() \
.filter("keys IS NOT NULL")
unique_keys_df.show()

# 2. Collect it as python list
unique_keys_list = [record.keys for record in unique_keys_df.rdd.collect()]
print(unique_keys_list)

"""
Output:

+-----+
| keys|
+-----+
|  age|
|blood|
|state|
+-----+

['age', 'blood', 'state']

"""

I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.

When should you use the PySpark map_keys() in Azure Databricks?

To get the keys of map columns in the form of an unordered array element.

Real World Use Case Scenarios for PySpark DataFrame map_keys() in Azure Databricks?

Assume you were given a DataFrame containing a MapType column called “preference” and having two keys, “pref1” and “pref2”. You’ve asked for the keys of each map value to be extracted into a list. This can be done by using the PySpark map_keys() function.

What are the alternatives to the map_keys() function in PySpark Azure Databricks?

The only way of collecting the keys of the MapType column is by using the map_keys() function, which is explained with an example in the above section.

Final Thoughts

In this article, we have learned about the PySpark map_keys() method of DataFrame in Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.

Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.

Arud Seka Berne S

As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.