簡體   English   中英

如何在Spark中使用多個鍵構建查找功能

[英]How to build a look up function with multiple keys in spark

我剛接觸火花 ,上周問了類似的問題。 它已編譯但不起作用。 所以我真的不知道該怎么辦。 這是我的問題:我的表A包含3列,像這樣

-----------
A1  A1  A3
-----------
a    b   c

另一個像這樣的表B

------------------------------------
B1  B2  B3  B4  B5  B6  B7  B8  B9
------------------------------------
1   a   3   4   5   b   7   8    c

我的邏輯是:A1 A2 A3是我的密鑰,它對應於表B中的B2 B6 B9。我需要構建一個以A1 A2 A3作為密鑰並返回我B8的查找函數。

這是我上周嘗試過的:

//getting the data in to dataframe
val clsrowRDD = clsfile.map(_.split("\t")).map(p => Row(p(0),p(1),p(2),p(3),p(4),p(5),p(6),p(7),p(8)))
val clsDataFrame = sqlContext.createDataFrame(clsrowRDD, clsschema)

//mapping the three key with the value
val smallRdd = clsDataFrame.rdd.map{row: Row => (mutable.WrappedArray.make[String](Array(row.getString(1), row.getString(5), row.getString(8))), row.getString(7))}

val lookupMap:Map[mutable.WrappedArray[String], String] = smallRdd.collectAsMap()

//build the look up function
def lookup(lookupMap: Map[mutable.WrappedArray[String],String]) =
udf((input: mutable.WrappedArray[String]) => lookupMap.lift(input))

//call the function
val combinedDF  = mstrDataFrame.withColumn("ENTP_CLS_CD",lookup(lookupMap)($"SRC_SYS_CD",$"ORG_ID",$"ORG_CD"))

這段代碼可以編譯,但是並沒有真正返回我所需的結果。 我在想這是因為我傳入了一個數組作為鍵,而我的表中卻沒有數組。 但是,當我嘗試將地圖類型更改為Map[(String,String,String),String] ,我不知道如何在函數中傳遞它。

謝謝。

如果您試圖為A1B2以及A2B6以及A3B9每次匹配獲取B8值,那么簡單的joinselect方法就可以解決問題。 創建查找圖會帶來復雜性。

正如您所解釋的,您必須將數據幀df1df2

+---+---+---+
|A1 |A2 |A3 |
+---+---+---+
|a  |b  |c  |
+---+---+---+

+---+---+---+---+---+---+---+---+---+
|B1 |B2 |B3 |B4 |B5 |B6 |B7 |B8 |B9 |
+---+---+---+---+---+---+---+---+---+
|1  |a  |3  |4  |5  |b  |7  |8  |c  |
|1  |a  |3  |4  |5  |b  |7  |8  |e  |
+---+---+---+---+---+---+---+---+---+

簡單的joinselect即可完成

df1.join(df2, $"A1" === $"B2" && $"A2" === $"B6" && $"A3" === $"B9", "inner").select("B8")

這應該給你

+---+
|B8 |
+---+
|8  |
+---+

我希望答案是有幫助的

更新

根據我從下面的問題和評論中了解的內容,您對如何將array傳遞給lookup udf函數感到困惑。 為此,您可以使用數組函數。 我已經修改了幾乎完美的代碼中的某些部分以使其正常工作

//mapping the three key with the value
val smallRdd = clsDataFrame.rdd
  .map{row: Row => (mutable.WrappedArray.make[String](Array(row.getString(1), row.getString(5), row.getString(8))), row.getString(7))}

val lookupMap: collection.Map[mutable.WrappedArray[String], String] = smallRdd.collectAsMap()

//build the look up function
def lookup(lookupMap: collection.Map[mutable.WrappedArray[String],String]) =
udf((input: mutable.WrappedArray[String]) => lookupMap.lift(input))

//call the function
val combinedDF  = mstrDataFrame.withColumn("ENTP_CLS_CD",lookup(lookupMap)(array($"SRC_SYS_CD",$"ORG_ID",$"ORG_CD")))

你應該有

+----------+------+------+-----------+
|SRC_SYS_CD|ORG_ID|ORG_CD|ENTP_CLS_CD|
+----------+------+------+-----------+
|a         |b     |c     |8          |
+----------+------+------+-----------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM