【问题标题】:Spark SQL - load data with JDBC using SQL statement, not table nameSpark SQL - 使用 SQL 语句使用 JDBC 加载数据,而不是表名
【发布时间】:2015-12-18 23:54:40
【问题描述】:

我想我错过了一些东西,但不知道是什么。 我想使用特定的 sql 语句使用 SQLContext 和 JDBC 加载数据 喜欢

select top 1000 text from table1 with (nolock)
where threadid in (
  select distinct id from table2 with (nolock)
  where flag=2 and date >= '1/1/2015' and  userid in (1, 2, 3)
)

我应该使用哪种 SQLContext 方法?我看到的示例总是指定表名和上下边距。

提前致谢。

【问题讨论】:

    标签: apache-spark apache-spark-sql


    【解决方案1】:

    您应该将有效的子查询作为dbtable 参数传递。例如在 Scala 中:

    val query = """(SELECT TOP 1000 
      -- and the rest of your query
      -- ...
    ) AS tmp  -- alias is mandatory*"""   
    
    val url: String = ??? 
    
    val jdbcDF = sqlContext.read.format("jdbc")
      .options(Map("url" -> url, "dbtable" -> query))
      .load()
    

    * Hive 语言手册子查询:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SubQueries

    【讨论】:

    • 谢谢。有效。我只是使用了 read.jdbc 而不是 read.format sqlContext.read.jdbc(url, table, prop)
    【解决方案2】:
    val url = "jdbc:postgresql://localhost/scala_db?user=scala_user"
    Class.forName(driver)
    
    val connection = DriverManager.getConnection(url)
    
    val df2 = spark.read
          .format("jdbc")
          .option("url", url)
          .option("dbtable", "(select id,last_name from emps) e")
          .option("user", "scala_user")
          .load()
    

    关键是“(select id,last_name from emps)e”,这里可以写一个子查询代替table_name。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2014-09-06
    • 2015-05-29
    相关资源
    最近更新 更多