【问题标题】:Combine two different RDDs with different key in Scala在Scala中结合两个不同的RDD和不同的键
【发布时间】:2021-12-02 02:20:51
【问题描述】:

我已经通过 sparkcontext 创建了两个文本文件作为 rdd。

其中一个(rdd1)保存相关词:

apple,apples
car,cars
computer,computers

另一个(rdd2)保存的项目数:

(apple,12)
(apples, 50)
(car,5)
(cars,40)
(computer,77)
(computers,11)

我想结合这两个rdds

不希望输出:

(apple, 62)
(car,45)
(computer,88)

如何编码?

【问题讨论】:

  • 嗨。你是新来的。您需要尝试一些事情并告诉我们您不了解的内容(我们不是来做您的功课的:)
  • 另外,创建 RDD(顺便说一句不是“保存”,RDD 是惰性的)并在问题中添加 .show 的输出。所以我们知道他们的架构
  • 如果你想在 Scala 中得到答案,为什么要标记 Java?

标签: scala apache-spark


【解决方案1】:

工作的重点是为相关词选择一个键。这里我只选择了第一个词,但实际上你可以做一些比随机选择更智能的事情。

解释:

  1. 创建数据
  2. 为相关词选择一个键
  3. 平面映射元组,使我们能够加入我们选择的键。
  4. 加入 RDD
  5. 将 RDD 映射回元组
  6. 按键归约
val s = Seq(("apple","apples"),("car","cars")) // create data
val rdd = sc.parallelize(s)
val t = Seq(("apple",12),("apples", 50),("car",5),("cars",40))// create data
val rdd2 = sc.parallelize(t)
val keyed = rdd.flatMap( {case(a,b) => Seq((a, a),(b,a)) } ) // could be replace with any function that selects the key to use for all of the related words
 .join(rdd2) // complete the join 
 .map({case (_, (a ,b)) => (a,b) }) // recreate a tuple and throw away the related word
 .reduceByKey(_ + _)
 .foreach(println) // to show it works

尽管这可以解决您的问题,但您可以使用更优雅的解决方案与您可能希望研究的 Dataframes 一起使用。您可以直接在 RDD 上使用 reduce 并跳过映射回元组的步骤。我认为这将是一个更好的解决方案,但希望保持简单,以便更能说明我所做的事情。

【讨论】:

    猜你喜欢
    • 2020-09-06
    • 2017-10-12
    • 2017-11-02
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多