首页 > 解决方案 > 如何在 for 循环中使用 Spark 随后在数据集中添加列(其中 for 循环包含列名)

问题描述

在这里尝试将后续列添加到数据集行,出现的问题是最后一列仅可见。之前添加的列不保留

private static void populate(Dataset<Row> res, String[] args)
    {
        String[] propArr = args[0].split(",");   // Eg: [abc, def, ghi]       
            
        // Dataset<Row> addColToMergedData = null;
        
        /** Here each element is the name of the column to be inserted */
        for(int i = 0; i < propArr.length; i++){

            // addColToMergedData = res.withColumn(propArr[i], lit(null));
        }
    }

标签: apache-spark-sqlapache-spark-dataset

解决方案


for 循环中的逻辑有缺陷,因此是问题所在。您可以按如下方式修改程序:

private static void populate(Dataset<Row> res, String[] args)
        {
                String[] propArr = args[0].split(",");   // Eg: [abc, def, ghi]       
               
                Dataset<Row> addColToMergedData = null;
        
                /** Here each element is the name of the column to be inserted */
                for(int i = 0; i < propArr.length; i++)
                {
                    res = res.withColumn(propArr[i], lit(null));
                }
                addColToMergedData  = res

        }

推荐阅读