Spark排序方式集錦


 一.簡介

  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 }

三.結果

  

  

  

  

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM