Spark SQL - 使用 JDBC 使用 SQL 语句加载数据,而不是 table 名称
Spark SQL - load data with JDBC using SQL statement, not table name
我想我遗漏了一些东西,但不知道是什么。
我想使用 SQLContext 和 JDBC 使用特定的 sql 语句加载数据
喜欢
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的哪个方法?我看到的示例总是指定 table 名称和下边距和上边距。
提前致谢。
您应该将有效的子查询作为 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
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.
我想我遗漏了一些东西,但不知道是什么。 我想使用 SQLContext 和 JDBC 使用特定的 sql 语句加载数据 喜欢
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的哪个方法?我看到的示例总是指定 table 名称和下边距和上边距。
提前致谢。
您应该将有效的子查询作为 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
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.