【问题标题】:Java-Spark: how to get a Dataset<Row> column's value when iterating in a loop and use it in when().otherwise()?Java-Spark:如何在循环中迭代时获取 Dataset<Row> 列的值并在 when().otherwise() 中使用它?
【发布时间】:2019-02-19 10:48:27
【问题描述】:

我有一个Dataset&lt;Row&gt;,其列的值为"null"(空文字)。
我正在尝试将 "null" 文本替换为文本:\N
为此,我使用了一个逻辑,我将添加一个名称附加“_nulled”的新列,例如abc 列变为 abc_nulled,如果当前值为文本 null,则此新列将具有值 "\N" > 否则价值保持不变。
为此,我使用了withColumn(&lt;new name&gt;, when(col.equalTo("null"), "\\N").otherwise(&lt;existing_value&gt;))。 我如何获得这个&lt;existing_value&gt;.
当我通过otherwise(ds.col(col_nm)) 时它不起作用,可能是因为它在otherwise() 中期待String 并找到Column

我应该如何解决这个问题?代码如下:

ArrayList<String> newCols = new ArrayList<String>();
List<String> reqColListCopy = Arrays.asList(reqCols);
Dataset<Row> testingDS = DS.selectExpr(JavaConverters.asScalaIteratorConverter(reqColListCopy.iterator()).asScala().toSeq())

//Creating newCols (ArrayList so that I can add/remove column names.
Iterator itrTmp2 = reqColListCopy.iterator();
while(itrTmp2.hasNext()){
    newCols.add((String)itrTmp2.next());
}

//Creating a List reference for newCols ArrayList. This will be used to get Seq(<columns>).
List<String> newColsList = newCols;

Iterator colListItr = reqColListCopy.iterator();
while(colListItr.hasNext())
{
    String col = colListItr.next().toString();
    testingDS = testingDS.selectExpr(convertListToSeq(newColsList))
            .withColumn(col+"_nulled",  functions.when(testingDS.col(col).equalTo("null"), functions.lit("\\N")).otherwise(testingDS.col(col))) //'otherwise' needs a string parameter
            .drop(testingDS.col(col));

    newCols.add(col+"_nulled");
    newCols.remove(col);
    newColsList = newCols;
}
Dataset<Row> testingDS = DS.selectExpr(JavaConverters.asScalaIteratorConverter(newColsList.iterator()).asScala().toSeq())

testingDS.show(false);

【问题讨论】:

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


    【解决方案1】:

    我通过在lit() 中传递列来解决它:

    .withColumn(col+"_nulled",  functions.when(testingDS.col(col).equalTo("null"), functions.lit("\\N")).otherwise(functions.lit(testingDS.col(col)))) //'otherwise' needs a string parameter
    

    【讨论】:

    • 是否有检查非空值的选项?我实际上希望将非空值放在引号中,并且不修改空值
    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 2020-05-11
    • 2018-04-15
    • 2019-07-05
    • 2020-10-21
    • 2017-11-17
    • 1970-01-01
    • 2016-03-16
    相关资源
    最近更新 更多