I have a Spark Dataset of the format -
+--------------+--------+-----+
|name |type |cost |
+--------------+--------+-----+
|AAAAAAAAAAAAAA|XXXXX |0.24|
|AAAAAAAAAAAAAA|YYYYY |1.14|
|BBBBBBBBBBBBBB|XXXXX |0.78|
|BBBBBBBBBBBBBB|YYYYY |2.67|
|BBBBBBBBBBBBBB|ZZZZZ |0.15|
|CCCCCCCCCCCCCC|XXXXX |1.86|
|CCCCCCCCCCCCCC|YYYYY |1.50|
|CCCCCCCCCCCCCC|ZZZZZ |1.00|
+--------------+--------+----+
I want to transform this into an object of type -
public class CostPerName {
private String name;
private Map<String, Double> costTypeMap;
}
What I want is,
+--------------+-----------------------------------------------+
|name | typeCost. |
+--------------+-----------------------------------------------+
|AAAAAAAAAAAAAA|(XXXXX, 0.24), (YYYYY, 1.14) |
|BBBBBBBBBBBBBB|(XXXXX, 0.78), (YYYYY, 2.67), (ZZZZZ, 0.15) |
|CCCCCCCCCCCCCC|(XXXXX, 1.86), (YYYYY, 1.50), (ZZZZZ, 1.00) |
+--------------+-----------------------------------------------+
i.e., for each name
, I want to a map of (type, cost)
.
What is an efficient way to achieve this transformation? Can I use some dataFrame transformation? I tried groupBy but that will only work if I am performing aggregate queries like sum, avg etc.
You can use a map_from_arrays()
if your Spark version allows it:
scala> val df2 = df.groupBy("name").agg(map_from_arrays(collect_list($"type"), collect_list($"cost")).as("typeCost"))
df2: org.apache.spark.sql.DataFrame = [name: string, typeCost: map<string,decimal(3,2)>]
scala> df2.printSchema()
root
|-- name: string (nullable = false)
|-- typeCost: map (nullable = true)
| |-- key: string
| |-- value: decimal(3,2) (valueContainsNull = true)
scala> df2.show(false)
+--------------+---------------------------------------------+
|name |typeCost |
+--------------+---------------------------------------------+
|AAAAAAAAAAAAAA|[XXXXX -> 0.24, YYYYY -> 1.14] |
|CCCCCCCCCCCCCC|[XXXXX -> 1.86, YYYYY -> 1.50, ZZZZZ -> 1.00]|
|BBBBBBBBBBBBBB|[XXXXX -> 0.78, YYYYY -> 2.67, ZZZZZ -> 0.15]|
+--------------+---------------------------------------------+
scala>