如何将hiveContext作为参数传递给函数spark scala

时间:2016-06-01 10:24:53

标签: scala apache-spark hivecontext

我在Scala中的hiveContext函数中创建了main(),我需要将此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()内调用。

任何想法?

2 个答案:

答案 0 :(得分:2)

我将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 = ...

另外,你的函数read应该接收HiveContext作为参数hc的类型,而不是hiveContext

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

答案 1 :(得分:1)

我尝试了几种选择,这最终对我有用..

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不可序列化的Excpetion。 好的,它最终以这种方式工作,我可以从DataFrame1的一行检索参数,并在加载DataFrame 2时使用这些值。