我有一个类型设置的列,并且我使用spark数据集API的collect_set(),该API返回包装好的包装数组。我想从嵌套包装的数组的所有值中得到一个数组。我怎样才能做到这一点?

例如。卡桑德拉表:

Col1
{1,2,3}
{1,5}


我正在使用Spark Dataset API。
row.get(0)返回包装数组的包装数组。

最佳答案

考虑您具有Dataset<Row> ds列的value列。

+-----------------------+
|value                  |
+-----------------------+
|[WrappedArray(1, 2, 3)]|
+-----------------------+


它具有以下架构

root
 |-- value: array (nullable = true)
 |    |-- element: array (containsNull = true)
 |    |    |-- element: integer (containsNull = false)


使用UDF

如下定义UDF1

static UDF1<WrappedArray<WrappedArray<Integer>>, List<Integer>> getValue = new UDF1<WrappedArray<WrappedArray<Integer>>, List<Integer>>() {
      public List<Integer> call(WrappedArray<WrappedArray<Integer>> data) throws Exception {
        List<Integer> intList = new ArrayList<Integer>();
        for(int i=0; i<data.size(); i++){
            intList.addAll(JavaConversions.seqAsJavaList(data.apply(i)));
        }
        return intList;
    }
};


注册并拨打UDF1如下

import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.callUDF;
import scala.collection.JavaConversions;

//register UDF
spark.udf().register("getValue", getValue, DataTypes.createArrayType(DataTypes.IntegerType));

//Call UDF
Dataset<Row> ds1  = ds.select(col("*"), callUDF("getValue", col("value")).as("udf-value"));
ds1.show();


使用爆炸功能

import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.explode;

Dataset<Row> ds2 = ds.select(explode(col("value")).as("explode-value"));
ds2.show(false);

关于java - WrapedArray的WrappedArray到Java数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45324530/

10-14 15:24
查看更多