Apache spark - 窗口函数,FIRST_VALUE不起作用

时间:2018-05-15 09:01:50

标签: apache-spark apache-spark-sql aggregation window-functions

我遇到WINDOW FUNCTION spark API的问题:

我的问题与此类似:How to drop duplicates using conditions

我有一个数据集:

+---+----------+---------+
| ID|    VALUEE|    OTHER|
+---+----------+---------+
|  1|      null|something|
|  1|[1.0, 0.0]|something|
|  1|[1.0, 0.0]|something|
|  1|[0.0, 2.0]|something|
|  1|[3.0, 5.0]|something|
|  2|[3.0, 5.0]|something|
|  1|[3.0, 5.0]|something|
|  2|      null|something|
|  3|[3.0, 5.0]|something|
|  4|      null|something|
+---+----------+---------+

我希望每个只保留一个ID(没有重复),我不关心VALUEE,但我更喜欢非NULL值

预期结果

+---+----------+---------+
| ID|    VALUEE|    OTHER|
+---+----------+---------+
|  1|[0.0, 2.0]|something|
|  3|[3.0, 5.0]|something|
|  4|      null|something|
|  2|[3.0, 5.0]|something|
+---+----------+---------+
使用Aggregate函数first()的windowsFunction不起作用 而对于row_number(),它可以工作

但我不明白为什么先不工作

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.*;
import org.apache.spark.sql.expressions.Window;
import org.apache.spark.sql.expressions.WindowSpec;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.spark_project.guava.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.apache.spark.sql.types.DataTypes.IntegerType;
import static org.apache.spark.sql.types.DataTypes.StringType;
import static org.apache.spark.sql.types.DataTypes.createStructField;

public class TestSOF {

    public static void main(String[] args) {

        StructType schema = new StructType(
                new StructField[]{
                        createStructField("ID", IntegerType, false),
                        createStructField("VALUEE", DataTypes.createArrayType(DataTypes.DoubleType), true),
                        createStructField("OTHER", StringType, true),
                });

        double [] a =new double[]{1.0,0.0};
        double [] b =new double[]{3.0,5.0};
        double [] c =new double[]{0.0,2.0};
        List<Row> listOfdata = new ArrayList();
        listOfdata.add(RowFactory.create(1,null,"something"));
        listOfdata.add(RowFactory.create(1,a,"something"));
        listOfdata.add(RowFactory.create(1,a,"something"));
        listOfdata.add(RowFactory.create(1,c,"something"));
        listOfdata.add(RowFactory.create(1,b,"something"));
        listOfdata.add(RowFactory.create(2,b,"something"));
        listOfdata.add(RowFactory.create(1,b,"something"));
        listOfdata.add(RowFactory.create(2,null,"something"));
        listOfdata.add(RowFactory.create(3,b,"something"));
        listOfdata.add(RowFactory.create(4,null,"something"));
        List<Row> rowList  = ImmutableList.copyOf(listOfdata);
        SparkSession sparkSession = new SparkSession.Builder().config("spark.master", "local[*]").getOrCreate();
        sparkSession.sparkContext().setLogLevel("ERROR");
        Dataset<Row> dataset = sparkSession.createDataFrame(rowList,schema);
        dataset.show();


        WindowSpec windowSpec = Window.partitionBy(dataset.col("ID")).orderBy(dataset.col("VALUEE").asc_nulls_last());

        // wind solution
        // lost information
        Dataset<Row> dataset0 = dataset.groupBy("ID").agg(functions.first(dataset.col("VALUEE"), true));

        Dataset<Row> dataset1 = dataset.withColumn("new",functions.row_number().over(windowSpec)).where("new = 1").drop("new");

        //do not work
        Dataset<Row> dataset2 = dataset.withColumn("new",functions.first("VALUEE",true).over(windowSpec)).drop("new");

        JavaRDD<Row> rdd =
                dataset.toJavaRDD()
                .groupBy(row -> row.getAs("ID"))
                .map(g -> {
                    Iterator<Row> iter =g._2.iterator();
                    Row rst = null;
                    Row tmp;
                    while(iter.hasNext()){
                        tmp = iter.next();
                        if (tmp.getAs("VALUEE") != null) {
                                rst=tmp;
                                break;
                        }
                        if(rst==null){
                            rst=tmp;
                        }
                    }
                    return rst;
                });

        Dataset<Row> dataset3 = sparkSession.createDataFrame(rdd, schema);

        dataset0.show();
        dataset1.show();
        dataset2.show();
        dataset3.show();
    }

}

3 个答案:

答案 0 :(得分:0)

对于您提供的示例数据,您提供的解决方案数据集1的简短版本:

dataset.groupBy("ID").agg(functions.first(dataset.col("VALUEE"), true)).show();

要了解Window Functions并优化Spark中WindowFunction vs groupBy的效果,我强烈推荐Jacek Laskowski的演示文稿:

  1. https://databricks.com/session/from-basic-to-advanced-aggregate-operators-in-apache-spark-sql-2-2-by-examples-and-their-catalyst-optimizations
  2. https://databricks.com/session/from-basic-to-advanced-aggregate-operators-in-apache-spark-sql-2-2-by-examples-and-their-catalyst-optimizations-continues

答案 1 :(得分:0)

您可以使用与发布的等效解决方案。在您的情况下,空值将以第一顺序出现。所以:

val df: DataFrame = ???

import df.sparkSession.implicits._
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.{col, last}

val id_cols = "ID"
val windowSpec = Window.partitionBy(id_cols).orderBy($"VALUEE".asc)
val list_cols = Seq("VALUE", "OTHER")

val df_dd = df.select(col(id_cols) +: list_cols.map(x => last(col(x)).over(windowSpec).alias(x)):_*).distinct

答案 2 :(得分:0)

在SPARK 2.3中,第一个不是Window函数,它只是一个聚合函数

firstValue在数据框API中不存在