gpt4 book ai didi

java - 使用 Java 在 Apache Spark 中的数据集的单列上应用函数

转载 作者:行者123 更新时间:2023-12-02 00:26:24 25 4
gpt4 key购买 nike

假设我有一个数据集:

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

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

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

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

如何使用 Java 上的 Apache Spark 来完成此操作?

最佳答案

我通过创建一个 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));

关于java - 使用 Java 在 Apache Spark 中的数据集的单列上应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com