Spark SQL Row_number() PartitionBy Sort Desc

后端 未结 3 1025
刺人心
刺人心 2021-02-01 15:50

I\'ve successfully create a row_number() partitionBy by in Spark using Window, but would like to sort this by descending, instead of the default ascend

相关标签:
3条回答
  • 2021-02-01 16:33

    Update Actually, I tried looking more into this, and it appears to not work. (in fact it throws an error). The reason why it didn't work is that I had this code under a call to display() in Databricks (code after the display() call is never run). It seems like the orderBy() on a dataframe and the orderBy() on a window are not actually the same. I will keep this answer up just for negative confirmation

    As of PySpark 2.4,(and probably earlier), simply adding in the keyword ascending=False into the orderBy call works for me.

    Ex.

    personal_recos.withColumn("row_number", F.row_number().over(Window.partitionBy("COLLECTOR_NUMBER").orderBy("count", ascending=False)))

    and

    personal_recos.withColumn("row_number", F.row_number().over(Window.partitionBy("COLLECTOR_NUMBER").orderBy(F.col("count").desc())))

    seem to give me the same behaviour.

    0 讨论(0)
  • 2021-02-01 16:37

    desc should be applied on a column not a window definition. You can use either a method on a column:

    from pyspark.sql.functions import col, row_number
    from pyspark.sql.window import Window
    
    F.row_number().over(
        Window.partitionBy("driver").orderBy(col("unit_count").desc())
    )
    

    or a standalone function:

    from pyspark.sql.functions import desc
    from pyspark.sql.window import Window
    
    F.row_number().over(
        Window.partitionBy("driver").orderBy(desc("unit_count"))
    )
    
    0 讨论(0)
  • 2021-02-01 16:38

    Or you can use the SQL code in Spark-SQL:

    from pyspark.sql import SparkSession
    
    spark = SparkSession\
        .builder\
        .master('local[*]')\
        .appName('Test')\
        .getOrCreate()
    
    spark.sql("""
        select driver
            ,also_item
            ,unit_count
            ,ROW_NUMBER() OVER (PARTITION BY driver ORDER BY unit_count DESC) AS rowNum
        from data_cooccur
    """).show()
    
    0 讨论(0)
提交回复
热议问题