gpt4 book ai didi

apache-spark - 高效计算spark中的top-k元素

转载 作者:行者123 更新时间:2023-12-04 05:09:57 28 4
gpt4 key购买 nike

我有一个数据框类似于:

+---+-----+-----+
|key|thing|value|
+---+-----+-----+
| u1| foo| 1|
| u1| foo| 2|
| u1| bar| 10|
| u2| foo| 10|
| u2| foo| 2|
| u2| bar| 10|
+---+-----+-----+

并希望得到以下结果:

+---+-----+---------+----+
|key|thing|sum_value|rank|
+---+-----+---------+----+
| u1| bar| 10| 1|
| u1| foo| 3| 2|
| u2| foo| 12| 1|
| u2| bar| 10| 2|
+---+-----+---------+----+

目前,有类似的代码:

val df = Seq(("u1", "foo", 1), ("u1", "foo", 2), ("u1", "bar", 10), ("u2", "foo", 10), ("u2", "foo", 2), ("u2", "bar", 10)).toDF("key", "thing", "value")

// calculate sums per key and thing
val aggregated = df.groupBy("key", "thing").agg(sum("value").alias("sum_value"))

// get topk items per key
val k = lit(10)
val topk = aggregated.withColumn("rank", rank over Window.partitionBy("key").orderBy(desc("sum_value"))).filter('rank < k)

但是,这段代码非常低效。窗口函数生成项目的总顺序并导致巨大的洗牌

如何更有效地计算前 k 个项目?也许使用近似函数,即类似于 https://datasketches.github.io/ 的草图或 https://spark.apache.org/docs/latest/ml-frequent-pattern-mining.html

最佳答案

这是推荐系统的经典算法。

case class Rating(thing: String, value: Int) extends Ordered[Rating] {
def compare(that: Rating): Int = -this.value.compare(that.value)
}

case class Recommendation(key: Int, ratings: Seq[Rating]) {
def keep(n: Int) = this.copy(ratings = ratings.sorted.take(n))
}

val TOPK = 10

df.groupBy('key)
.agg(collect_list(struct('thing, 'value)) as "ratings")
.as[Recommendation]
.map(_.keep(TOPK))

您还可以在以下位置查看源代码:

  • Spotify 大数据 Rosetta 代码/TopItemsPerUser.scala , 这里有几个针对 Spark 或 Scio 的解决方案
  • Spark MLLib/TopByKeyAggregator.scala ,被认为是使用他们的推荐算法时的最佳实践,但看起来他们的示例仍然使用 RDD
import org.apache.spark.mllib.rdd.MLPairRDDFunctions._

sc.parallelize(Array(("u1", ("foo", 1)), ("u1", ("foo", 2)), ("u1", ("bar", 10)), ("u2", ("foo", 10)),
("u2", ("foo", 2)), ("u2", ("bar", 10))))
.topByKey(10)(Ordering.by(_._2))

关于apache-spark - 高效计算spark中的top-k元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56270629/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com