Generate a single row dataframe for lookup

Viewed 131

This is a follow up question that I posted previously.

Step 1:

scala> spark.sql("select map('s1', 'p1', 's2', 'p2', 's3', 'p3') as lookup").show()
+--------------------+
|              lookup|
+--------------------+
|[s1 -> p1, s2 -> ...|
+--------------------+

Step 2:

scala> val df = Seq(("s1", "p1"), ("s2", "p2"), ("s3", "p3")).toDF("s", "p")
df: org.apache.spark.sql.DataFrame = [s: string, p: string]

scala> df.show()
+---+---+
|  s|  p|
+---+---+
| s1| p1|
| s2| p2|
| s3| p3|
+---+---+

Step 3:

scala> val df1 = df.selectExpr("map(s,p) lookup")
df1: org.apache.spark.sql.DataFrame = [cc: map<string,string>]

scala> df1.show()
+----------+
|    lookup|
+----------+
|[s1 -> p1]|
|[s2 -> p2]|
|[s3 -> p3]|
+----------+

My expected result in step3 is the result I am getting in step1. How can I achieve it?

1 Answers

The two columns for the key and value should be aggregated into arrays before merging them into a map.

import org.apache.spark.sql.functions._

df.agg(collect_list("s").as("s"), collect_list("p").as("p"))
    .select(map_from_arrays('s,'p).as("lookup"))
    .show(false)

Output:

+------------------------------+
|lookup                        |
+------------------------------+
|[s1 -> p1, s2 -> p2, s3 -> p3]|
+------------------------------+

Without the collect_list calls, each row will be transformed individually into a map.

Related