摘要
Window是一个窗口函数,用于将数据进行划分。
生成数据
val ori = Seq(
("zhang","san",56,170),
("zhang","si",60,172),
("liu","san",54,182),
("liu","wu",65,167),
("zhang","san",78,183)
).toDF("surname","name","weight","height")
ori.cache()
ori.show()
partitionBy函数
用于对数据进行分区,参数是分区的列名。多个列名用逗号隔开
import org.apache.spark.sql.expressions.Window
val res1 = Window.partitionBy("surname")
val res2 = ori.withColumn("max",max("height").over(res1))
res2.show()
orderBy函数
将分区之后的数据按照参数进行排序
import org.apache.spark.sql.expressions.Window
val res1 = Window.partitionBy("surname").orderBy("height")
val res2 = ori.withColumn("max",max("height").over(res1))
res2.show()
rowsBetween
指定分区排序之后进行操作时,操作的数据范围。有两个参数,第一个指定操作的起始位置,第二个指定操作的最后位置。
Window.unboundedPreceding:分区的开始位置
Window.currentRow:分区计算到现在的位置
Window.unboundedFollowing:分区的最后位置。
负数:表示若前面有元素,范围向前延申几个元素
0:表示当前位置,等价于Window.currentRow
正数:表示若后面有元素,范围向后延申几个元素
import org.apache.spark.sql.expressions.Window
val res1 = Window.partitionBy("surname").orderBy("height").rowsBetween(Window.unboundedPreceding,Window.unboundedFollowing)
val res2 = ori.withColumn("max",max("height").over(res1))
res2.show()