我有兩個文本檔案已經由 sparkcontext 創建為 rdd。
其中一個(rdd1)保存相關詞:
apple,apples
car,cars
computer,computers
另一個(rdd2)保存專案數:
(apple,12)
(apples, 50)
(car,5)
(cars,40)
(computer,77)
(computers,11)
我想結合這兩個 rdd
危險輸出:
(apple, 62)
(car,45)
(computer,88)
如何編碼?
uj5u.com熱心網友回復:
作業的重點是為相關詞選擇一個關鍵。在這里,我只選擇第一個單詞,但實際上你可以做一些比隨機選擇一個詞更聰明的事情。
解釋:
- 創建資料
- 為相關詞選擇一個鍵
- 對元組進行平面映射,使我們能夠加入我們選擇的鍵。
- 加入 RDD
- 將 RDD 映射回元組
- 按鍵減少
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 并跳過映射回元組的步驟。我認為這將是一個更好的解決方案,但希望保持簡單,以便更能說明我所做的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/318740.html
