【问题标题】:Apply function on a single column of a Dataset in Apache Spark using Java使用 Java 在 Apache Spark 中的数据集的单个列上应用函数
【发布时间】:2019-10-21 05:26:53
【问题描述】:

假设我有一个数据集:

Dataset<Row> sqlDF = this.spark.sql("SELECT first_name, last_name, age from persons";

这将返回一个包含三列的Dataset:first_name、last_name、age。

我想应用一个函数,将 5 添加到 age 列并返回一个与原始数据集具有相同列但年龄值更改的新数据集:

public int add_age(int old_age){
     return old_age + 5;
}

如何在 Java 上使用 Apache Spark?

【问题讨论】:

    标签: java apache-spark apache-spark-sql apache-spark-dataset


    【解决方案1】:

    我通过创建一个 StructType 并将三列添加到其中解决了这个问题,然后将每一列映射到新构造的行并使用 RowFactory 将函数应用于行列 age

        StructType customStructType = new StructType();
    
        customStructType = customStructType.add("first_name", DataTypes.StringType, true);
        customStructType = customStructType.add("last_name", DataTypes.StringType, true);
        customStructType = customStructType.add("age", DataTypes.IntegerType, true);
    
        ExpressionEncoder<Row> customTypeEncoder = null;
        Dataset<Row> changed_data = sqlDF.map(row->{
              return RowFactory.create(row.get(0),row.get(1), add_age(row.get(2)));
                }, RowEncoder.apply(customStructType));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多