簡體   English   中英

如何將hiveContext作為參數傳遞給函數spark scala

[英]How to pass hiveContext as argument to functions spark scala

我在Scala的main()函數中創建了一個hiveContext ,我需要將此hiveContext參數hiveContext給其他函數,這是結構:

object Project {
    def main(name: String): Int = {
      val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
      ... 
    } 
    def read (streamId: Int, hc:hiveContext): Array[Byte] = {
    ... 
    } 
    def close (): Unit = {
    ...
    }
 }

但這不起作用。 函數read()main()內部調用。

任何想法?

我將hiveContext聲明為隱式,這對我有用

implicit val sqlContext: HiveContext = new HiveContext(sc)
MyJob.run(conf)

在MyJob中定義:

override def run(config: Config)(implicit sqlContext: SQLContext): Unit = ...

但是,如果您不希望它隱式,則應該相同

val sqlContext: HiveContext = new HiveContext(sc)
MyJob.run(conf)(sqlContext)

override def run(config: Config)(sqlContext: SQLContext): Unit = ...

另外,您讀取的函數應接收HiveContext作為參數hc的類型,而不是hiveContext

def read (streamId: Int, hc:HiveContext): Array[Byte] = 

我嘗試了幾種選擇,這最終對我有用。

object SomeName extends App {

val conf = new SparkConf()...
val sc = new SparkContext(conf)

implicit val sqlC = SQLContext.getOrCreate(sc)
getDF1(sqlC)

def getDF1(sqlCo: SQLContext): Unit = {
    val query1 =  SomeQuery here  
    val df1 = sqlCo.read.format("jdbc").options(Map("url" -> dbUrl,"dbtable" -> query1)).load.cache()

 //iterate through df1 and retrieve the 2nd DataFrame based on some values in the Row of the first DataFrame

  df1.foreach(x => {
    getDF2(x.getString(0), x.getDecimal(1).toString, x.getDecimal(3).doubleValue) (sqlCo)
  })     
}

def getDF2(a: String, b: String, c: Double)(implicit sqlCont: SQLContext) :  Unit = {
  val query2 = Somequery

  val sqlcc = SQLContext.getOrCreate(sc)
  //val sqlcc = sqlCont //Did not work for me. Also, omitting (implicit sqlCont: SQLContext) altogether did not work
  val df2 = sqlcc.read.format("jdbc").options(Map("url" -> dbURL, "dbtable" -> query2)).load().cache()
   .
   .
   .
 }
}

注意:在上面的代碼中,如果我從getDF2方法簽名中省略了(隱式sqlCont:SQLContext)參數,它將無法正常工作。 我嘗試了將sqlContext從一種方法傳遞給另一種方法的其他幾種選擇,但它總是給我NullPointerException或Task not serializable Excpetion。 好瘦了,它最終以這種方式工作了,我可以從DataFrame1的一行中檢索參數,並在加載DataFrame 2時使用這些值。

暫無
暫無

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

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