Spark DataFrame join后移除重复的列

在Spark,两个DataFrame做join操作后,会出现重复的列。例如:

 Dataset<Row> moviesWithRating = moviesDF
                .join(averageRatingMoviesDF,
                        moviesDF.col("movieId").equalTo(averageRatingMoviesDF.col("movieId")));

其schema如下:

//moviesWithRating.printSchema();
        /**
         * root
         *  |-- _id: struct (nullable = true)
         *  |    |-- oid: string (nullable = true)
         *  |-- actors: string (nullable = true)
         *  |-- description: string (nullable = true)
         *  |-- directors: string (nullable = true)
         *  |-- genres: string (nullable = true)
         *  |-- issue: string (nullable = true)
         *  |-- language: string (nullable = true)
         *  |-- movieId: integer (nullable = true)
         *  |-- shoot: string (nullable = true)
         *  |-- timeLong: string (nullable = true)
         *  |-- title: string (nullable = true)
         *  |-- movieId: integer (nullable = true)
         *  |-- avgRating: double (nullable = true)
         */

我们在继续操作这个DataFrame时,可能就会报错,如下:org.apache.spark.sql.AnalysisException: Reference ‘movieId’ is ambiguous

解决方案有两种方法可以用来移除重复的列

  • 方法一:join表达式使用字符串数组(用于join的列)
Seq<String> joinColumns = JavaConversions.asScalaBuffer(Arrays.asList("movieId")).toList();
Dataset<Row> moviesWithRating = moviesDF.join(
                        averageRatingMoviesDF,
                        joinColumns,
                        "inner");

这里DataFrame moviesDF和averageRatingMoviesDF使用了movieId和movieId两列来做join,返回的结果会对这两列去重
如果是scala,解决方案如下:

 val moviesWithRating = moviesDf.join(averageRatingMoviesDF, Seq("movieId")) 
  • 方法二:使用select返回指定的列
Dataset<Row> moviesWithRating = moviesDF
                .join(averageRatingMoviesDF,
                        moviesDF.col("movieId").equalTo(averageRatingMoviesDF.col("movieId")))
                .select(
                        moviesDF.col("movieId"),

                        col("actors"),
                        col("description"),
                        col("directors"),
                        col("genres"),
                        col("issue"),
                        col("language"),
                        col("shoot"),
                        col("timeLong"),
                        col("title"),
                        col("avgRating")
                );

说明:
如果列较少, 推荐使用第二种.
如果列较多, 推荐使用第一种.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值