类型不匹配:预期的字符串,实际的列

Type mismatch: expected String, actual Column

我正在使用 Spark 2.2.0 和 Scala 2.11 对我的 DataFrame 进行一些转换。

这行代码出现问题Math.abs($"right.product_price".asInstanceOf[Double] - $"left.product_price".asInstanceOf[Double])。我想计算 left.product_priceright.product_price 之间的绝对差值。如果其中任何列包含 null,则 null 将转换为 0

但是,我得到一个错误:"Type mismatch: expected String, actual Column"。 我怎样才能以正确的方式进行这个计算?

val result = df.as("left")
    // self-join by gender:
    .join(df.as("right"), ($"left.gender" === $"right.gender")
    // limit to 10 results per record:
    .withColumn("rn", row_number().over(Window.partitionBy($"left.product_PK").orderBy($"right.product_PK")))
    .filter($"rn <= 10").drop($"rn")
    // group and collect_list to create products column:
    .groupBy($"left.product_PK" as "product_PK")
    .agg(collect_list(struct($"right.product_PK", Math.abs($"right.product_price".asInstanceOf[Double] - $"right.product_price".asInstanceOf[Double]))) as "products")

您不能使用 Math.abs,也不能使用 asinstanceOf。使用 SQL functions.abscast:

import org.apache.spark.sql.functions.abs

...
  .agg(collect_list(struct(
     $"right.product_PK",
    abs($"right.product_price".cast("double)" - $"right.product_price".cast("double"))
  )) as "products")

要将 null 转换为 0 添加 coalesce:

import org.apache.spark.sql.functions.{coalesce, lit}

coalesce(column, lit(0))