【问题标题】:Spark: Create temporary table by executing sql query on temporary tablesSpark:通过对临时表执行 sql 查询来创建临时表
【发布时间】:2018-06-20 13:46:20
【问题描述】:

我正在使用 Spark,我想知道:如何通过对表 A 和 B 执行 sql 查询来创建名为 C 的临时表?

sqlContext
   .read.json(file_name_A)
   .createOrReplaceTempView("A")

sqlContext
   .read.json(file_name_B)
   .createOrReplaceTempView("B")

val tableQuery = "(SELECT A.id, B.name FROM A INNER JOIN B ON A.id = B.fk_id) C"

sqlContext.read
   .format(SQLUtils.FORMAT_JDBC)
   .options(SQLUtils.CONFIG())
   .option("dbtable", tableQuery)
   .load()

【问题讨论】:

    标签: scala apache-spark jenkins jdbc


    【解决方案1】:

    您需要将结果保存为临时表

    tableQuery .createOrReplaceTempView("dbtable")
    

    外部表上的永久存储,您可以使用 JDBC

    val prop = new java.util.Properties
    prop.setProperty("driver", "com.mysql.jdbc.Driver")
    prop.setProperty("user", "vaquar")
    prop.setProperty("password", "khan") 
     
    //jdbc mysql url - destination database is named "temp"
    val url = "jdbc:mysql://localhost:3306/temp"
     
    //destination database table 
    val dbtable = "sample_data_table"
     
    //write data from spark dataframe to database
    df.write.mode("append").jdbc(url, dbtable, prop)
    

    https://docs.databricks.com/spark/latest/data-sources/sql-databases.html

    http://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

    【讨论】:

      【解决方案2】:
      sqlContext.read.json(file_name_A).createOrReplaceTempView("A")
      sqlContext.read.json(file_name_B).createOrReplaceTempView("B")
      val tableQuery = "(SELECT A.id, B.name FROM A INNER JOIN B ON A.id = B.fk_id) C"
      sqlContext.sql(tableQuery).createOrReplaceTempView("C")
      

      试试上面的代码就行了。

      【讨论】:

      • 你的答案是有效的,不幸的是我不能使用 sqlContext.sql 因为它不会执行数据库中的整个请求。实际上,sqlContext.sql 可以将查询拆分为两个选择,然后在不同的工作人员上执行连接。在我的情况下,工人没有足够的内存来处理它并且他们崩溃了......
      猜你喜欢
      • 2013-07-01
      • 2023-01-20
      • 2013-07-10
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 2023-03-03
      相关资源
      最近更新 更多