Spark Couldn't Find Window Function

浪尽此生 提交于 2019-12-12 02:46:06

问题


Using the solution provided in https://stackoverflow.com/a/32407543/5379015 I tried to recreate the same query but using the programmatic syntax in stead of the Dataframe API as follows:

import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

object HiveContextTest {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("HiveContextTest")
    val sc = new SparkContext(conf)
    val sqlContext = new HiveContext(sc)
    import sqlContext.implicits._

    val df = sc.parallelize(
      ("foo", 1) :: ("foo", 2) :: ("bar", 1) :: ("bar", 2) :: Nil
    ).toDF("k", "v")


    // using dataframe api works fine

    val w = Window.partitionBy($"k").orderBy($"v")
    df.select($"k",$"v", rowNumber().over(w).alias("rn")).show


    //using programmatic syntax doesn't work

    df.registerTempTable("df")
    val w2 = sqlContext.sql("select k,v,rowNumber() over (partition by k order by v) as rn from df")
    w2.show()

  }
}

The first df.select($"k",$"v", rowNumber().over(w).alias("rn")).show works fine but the w2.show() results in

Exception in thread "main" org.apache.spark.sql.AnalysisException: Couldn't find window function rowNumber;

Does anyone have any ideas as to how I can make this work with the programmatic syntax? Many thanks in advance.


回答1:


SQL equivalent of rowNumber is row_number:

SELECT k, v, row_number() OVER (PARTITION BY k ORDER BY v) AS rn FROM df


来源:https://stackoverflow.com/questions/32905443/spark-couldnt-find-window-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!