How to collect map values in PySpark Azure Databricks?

Are you looking to find out how to collect values 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 values into a python list of PySpark Databricks using the map_values() 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_values() 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_values() function in PySpark.

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

  • Syntax of map_values() function
  • Getting the values from a MapType column
  • Getting unique values of certain data type from a MapType column

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

Syntax:

map_values()

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

The syntax is as follows:

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

Apache Spark Official Documentation Link: map_values()

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": "24", "blood": None, "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 -> null, age -> 24}|
|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 values from a MapType column of PySpark DataFrame using Azure Databricks?

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

Example:

from pyspark.sql.functions import map_values

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

"""
Output:

+----------------+
|map_values(info)|
+----------------+
|        [B+, 23]|
|        [B+, 24]|
|  [TN, null, 24]|
|            null|
+----------------+

"""

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

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

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

Example:

from pyspark.sql.functions import map_values, explode

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

# 2. Collecting all the numeric value out of all values
unique_values_list = [record.values for record in unique_values_df.rdd.collect() if record.values.isnumeric()]
print(unique_values_list)

"""
Output:

+------+
|values|
+------+
|    23|
|    B+|
|    24|
|    TN|
+------+

['23', '24']

"""

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_values() in Azure Databricks?

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

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

Assume you were given a DataFrame containing a MapType column called “preference” and having two keys, “age” and “state”. You’ve asked for the values of each key to be extracted into a list for checking purposes. This can be done by using the PySpark map_values() function.

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

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

Final Thoughts

In this article, we have learned about the PySpark map_values() 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.