ant*_*ell 2 scala group-by aggregate-functions apache-spark apache-spark-sql
我想知道是否有某种方法为Spark数据帧指定自定义聚合函数.如果我有一个包含2列的表id,value我想groupBy id并将值聚合到每个列表中,value如下所示:
从:
john | tomato
john | carrot
bill | apple
john | banana
bill | taco
Run Code Online (Sandbox Code Playgroud)
至:
john | tomato, carrot, banana
bill | apple, taco
Run Code Online (Sandbox Code Playgroud)
这在数据帧中是否可行?我问的是数据帧,因为我正在将数据作为一个orc文件读取,并将其作为数据帧加载.我认为将它转换为RDD是无效的.
我只想简单介绍以下内容:
import org.apache.spark.sql.functions.collect_list
val df = Seq(("john", "tomato"), ("john", "carrot"),
("bill", "apple"), ("john", "banana"),
("bill", "taco")).toDF("id", "value")
// df: org.apache.spark.sql.DataFrame = [id: string, value: string]
val aggDf = df.groupBy($"id").agg(collect_list($"value").as("values"))
// aggDf: org.apache.spark.sql.DataFrame = [id: string, values: array<string>]
aggDf.show(false)
// +----+------------------------+
// |id |values |
// +----+------------------------+
// |john|[tomato, carrot, banana]|
// |bill|[apple, taco] |
// +----+------------------------+
Run Code Online (Sandbox Code Playgroud)
你甚至不需要调用底层证券rdd.
| 归档时间: |
|
| 查看次数: |
362 次 |
| 最近记录: |