首页 > 解决方案 > 优化一段使用地图动作的代码

问题描述

以下代码在集群中的 4Gb 原始数据上花费了大量时间:

df.select("type", "user_pk", "item_pk","timestamp")
      .withColumn("date",to_date(from_unixtime($"timestamp")))
      .filter($"date" > "2018-04-14")
      .select("type", "user_pk", "item_pk")
      .map {
        row => {
          val typef = row.get(0).toString
          val user = row.get(1).toString
          val item = row.get(2).toString
          (typef, user, item)
        }
      }

输出应该是类型Dataset[(String,String,String)]

我想这map部分需要很多时间。有没有办法优化这段代码?

标签: scalaapache-sparkapache-spark-sqlapache-spark-dataset

解决方案


我严重怀疑map是问题所在,但我根本不会使用它并使用标准Dataset转换器

import df.sparkSession.implicits._

df.select("type", "user_pk", "item_pk","timestamp")
  .withColumn("date",to_date(from_unixtime($"timestamp")))
  .filter($"date" > "2018-04-14")
  .select($"type" cast "string", $"user_pk" cast "string", $"item_pk" cast "string")
  .as[(String,String,String)]

推荐阅读