在 Spark Scala 中映射和删除重复项?

Mapping and removing duplicates in Spark Scala?

我有一个数据集test.txt。它包含如下数据

1::1::3
1::1::2
1::2::2
2::1::5
2::1::4
2::2::2
3::1::1
3::2::2

我使用以下代码创建了数据框。

case class Rating(userId: Int, movieId: Int, rating: Float)
def parseRating(str: String): Rating = {
val fields = str.split("::")
assert(fields.size == 3)
Rating(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/cravi/Desktop/test.txt").map(parseRating).toDF()

但是当我尝试打印输出时,我的输出低于输出

[1,1,3.0]
[1,1,2.0]
[1,2,2.0]
[2,1,2.0]
[2,1,4.0]
[2,2,2.0]
[3,1,1.0]
[3,2,2.0]

但我想打印如下所示的输出,即删除重复的组合而不是 field(2) value 1.0.

[1,1,1.0]
[1,2,1.0]
[2,1,1.0]
[2,2,1.0]
[3,1,1.0]
[3,2,1.0]

创建 dataframe 后,可以通过调用 .dropDuplicates(columnNames) 删除重复项,使用 lit 和 [ 可以用 1.0 填充第三列=16=] 函数。

综上所述,简单的解决方法如下

val ratings = sc.textFile("C:/Users/cravi/Desktop/test.txt")
    .map(line => line.split("::"))
    .filter(fields => fields.length == 3)
    .map(fields => Rating(fields(0).toInt, fields(1).toInt, 1.0f))
  .toDF().dropDuplicates("userId", "movieId")

ratings.show(false)

哪个应该给你

+------+-------+------+
|userId|movieId|rating|
+------+-------+------+
|3     |1      |1.0   |
|2     |2      |1.0   |
|1     |2      |1.0   |
|1     |1      |1.0   |
|2     |1      |1.0   |
|3     |2      |1.0   |
+------+-------+------+