如何将spark数据集的所有列强制转换为java中的字符串而不使用withcolumn?

vh0rcniy  于 2021-05-19  发布在  Spark
关注(0)|答案(1)|浏览(478)

我尝试了使用此处指定的withcolumn的解决方案:
如何使用java将spark数据集的所有列强制转换为字符串
但是,解决方案会对大量列(1k-6k)的性能造成影响。它需要6个多小时,然后被中止。
或者,我尝试使用map进行如下的强制转换,但是我在这里得到了一个错误:

MapFunction<Column, Column> mapFunction = (c) -> {
    return c.cast("string");
};      

dataset = dataset.map(mapFunction, Encoders.bean(Column.class));

以上代码段出错:

The method map(Function1<Row,U>, Encoder<U>) in the type Dataset<Row> is not applicable for the arguments (MapFunction<Column,Column>, Encoder<Column>)

使用的导入:

import org.apache.spark.api.java.function.MapFunction;

已更新-找到解决方案

String[] strColNameArray = dataset.columns();
    List<Column> colNames = new ArrayList<>();
    for(String strColName : strColNameArray){
        colNames.add(new Column(strColName).cast("string"));
    }
    dataset = dataset.select(JavaConversions.asScalaBuffer(colNames));`
wz8daaqr

wz8daaqr1#

你确定是指1k-6k列还是行?
但在任何情况下,我一般都会这样铸造柱:

import spark.implicits._

val df = Seq((1, 2), (2, 3), (3, 4)).toDF("a", "b")

val cols = for {
  a <- df.columns
} yield col(a).cast(StringType)

df.select(cols : _*)

相关问题