Spark DataFrame join后移除重复的列

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

java 复制代码
 Dataset<Row> moviesWithRating = moviesDF
                .join(averageRatingMoviesDF,
                        moviesDF.col("movieId").equalTo(averageRatingMoviesDF.col("movieId")));

其schema如下:

java 复制代码
//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的列)
java 复制代码
Seq<String> joinColumns = JavaConversions.asScalaBuffer(Arrays.asList("movieId", "movieId")).toList();
        Dataset<Row> moviesWithRating = moviesDF
                .join(
                        averageRatingMoviesDF,
                        joinColumns,
                        "inner");

这里DataFrame moviesDF和averageRatingMoviesDF使用了movieId和movieId两列来做join,返回的结果会对这两列去重

scala解决方案:

scala 复制代码
df1.join(df2, Seq("id","name"),"left")  // df1和df2使用了id和name两列来做join,返回的结果会对这两列去
  • 方法二:使用select返回指定的列
java 复制代码
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")
                );

说明:

如果列较少, 推荐使用第二种.

如果列较多, 推荐使用第一种.

相关推荐
大大大大晴天1 天前
Hudi技术内幕:RecordPayload到RecordMerger
大数据
SelectDB2 天前
秒级弹性、最高降本 70%:SelectDB Serverless 如何重塑云数仓资源效率
大数据·后端·云原生
WhoAmI2 天前
MapReduce框架原理解析一:InputFormat
大数据·hadoop
WhoAmI2 天前
MapReduce框架原理解析三:OutputFormat
大数据·hadoop
WhoAmI2 天前
MapReduce框架原理解析二:Shuffle
大数据·hadoop
大大大大晴天3 天前
Hudi技术内幕:Key Generation原理与实践
大数据
得物技术6 天前
从埋点需求到规则资产:Hermes Agent 重构得物数仓工作流
大数据·llm·ai编程
久美子6 天前
AI驱动数仓建设的Harness工程实践——本体建模、知识分层与上下文工程
大数据
大树887 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
大志哥1237 天前
ES和Logstash日志链路系统上线后遭遇切片爆炸(解决)
大数据·elasticsearch