一.简介
spark中的排序一般可以使用orderBy或sort算子,可以结合负号、ASC/DESC和col进行简单排序、二次排序等情况
二.代码实现
1 package big.data.analyse.sparksql
2
3 import org.apache.log4j.{Level, Logger}
4 import org.apache.spark.sql.SparkSession
5
6 /**
7 * 排序
8 * Created by zhen on 2019/8/14.
9 */
10 object DateFrameSort {
11 Logger.getLogger("org").setLevel(Level.WARN)
12 def main(args: Array[String]): Unit = {
13 val spark = SparkSession.builder().appName("DateFrameSort").master("local[2]").getOrCreate()
14
15 val data = Array((7, 2, 3), (1, 8, 6), (1, 8, 3), (4, 5, 9))
16 val df = spark.createDataFrame(data).toDF("col1", "col2", "col3")
17 println("===原始数据===")
18 df.show()
19 println("===按照col1,col2进行默认排序===")
20 // 默认的升序,会按照列的先后顺序进行升序排序
21 df.orderBy("col2", "col3").show()
22 println("===按照-df(col1)进行升序排序===")
23 /**
24 * 此排序方式需要提前创建好df,不能在创建df时使用
25 */
26 df.orderBy(-df("col2")).show
27 println("===按照df(col1).asc,df(col2).desc进行二次排序===")
28 /**
29 * 二次排序
30 * -号和desc/asc不能在一块使用
31 */
32 df.orderBy(df("col1").asc,df("col2").desc).show
33 println("===asc/desc排序方法===")
34
35 /**
36 * 使用desc等算子需要预先导入
37 */
38 import org.apache.spark.sql.functions._
39
40 df.orderBy(asc("col2")).show
41 spark.createDataFrame(data).toDF("col1", "col2", "col3").orderBy(desc("col2")).show
42 df.orderBy(asc("col2"), desc("col3")).show
43 /**
44 * sort函数和orderBy用法类似
45 */
46 df.sort(desc("col2")).show
47 println("===col组合asc/desc排序方法===")
48 df.orderBy(-col("col2")).show
49 df.orderBy(col("col2").desc).show
50 /**
51 * 第二列无效
52 * -号和desc/asc不能在一个orderBy使用
53 */
54 df.orderBy(col("col2").desc, -col("col3")).show
55 spark.stop()
56 }
57 }
三.结果





