【发布时间】:2017-07-20 21:51:57
【问题描述】:
我在 Stackoverflow 上找到了类似的帖子。但是,我无法解决我的问题所以,这就是我写这篇文章的原因。
瞄准
目的是在加载 SQL 表(我使用 SQL Server)时执行列投影 [projection = filter columns]。
根据 scala 食谱,这是 [使用数组] 过滤列的方法:
sqlContext.read.jdbc(url,"person",Array("gender='M'"),prop)
但是,我不想在我的 Scala 代码中硬编码 Array("col1", "col2", ...) 这就是为什么我使用具有类型安全的配置文件(见下文)。
配置文件
dataset {
type = sql
sql{
url = "jdbc://host:port:user:name:password"
tablename = "ClientShampooBusinesLimited"
driver = "driver"
other = "i have a lot of other single string elements in the config file..."
columnList = [
{
colname = "id"
colAlias = "identifient"
}
{
colname = "name"
colAlias = "nom client"
}
{
colname = "age"
colAlias = "âge client"
}
]
}
}
让我们关注“columnList”:SQL 列的名称与“colname”完全对应。 'colAlias' 是我稍后将使用的字段。
data.scala 文件
lazy val columnList = configFromFile.getList("dataset.sql.columnList")
lazy val dbUrl = configFromFile.getList("dataset.sql.url")
lazy val DbTableName= configFromFile.getList("dataset.sql.tablename")
lazy val DriverName= configFromFile.getList("dataset.sql.driver")
configFromFile 是我自己在另一个自定义类中创建的。但这没关系。 columnList 的类型是“ConfigList”,这个类型来自于 typesafe。
主文件
def loadDataSQL(): DataFrame = {
val url = datasetConfig.dbUrl
val dbTablename = datasetConfig.DbTableName
val dbDriver = datasetConfig.DriverName
val columns = // I need help to solve this
/* EDIT 2 march 2017
This code should not be used. Have a look at the accepted answer.
*/
sparkSession.read.format("jdbc").options(
Map("url" -> url,
"dbtable" -> dbTablename,
"predicates" -> columns,
"driver" -> dbDriver))
.load()
}
所以我所有的问题都是提取“colnames”值,以便将它们放入合适的数组中。有人可以帮我写出“val columns”的正确操作吗?
谢谢
【问题讨论】:
标签: arrays scala apache-spark typesafe