scala 如何在使用类型安全配置时将参数传递给Spark SQL查询

llew8vvj  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(183)

无法实现字符串内插。我的Daily_query.conf文件和代码如下所示

metrics {
opt_metrics{
query= """select * from opt where created_at= '$ds'"""
}

}

val config: Config = ConfigFactory.load("daily_query.conf").getConfig("metrics")

val ds = "2022-10-30"

val rawQuery = config.getString("opt_metrics.query")

val q = "s""""+rawQuery+"""""

println(q) //output: s"""select * from opt where created_at= '$ds'"""

预期的结果是替换变量‘ds’的值,如spak.sql(s“SELECT*FROM OPT WHERE CREATED_AT=‘2022-10-30’”)。

vuktfyat

vuktfyat1#

字符串内插器在编译时使用宏来展开(请参见此处)。这意味着,在读取配置文件时以编程方式使用它们的唯一方法是自己使用宏(尽管我也不能100%确定这是否真的可行)。对于您想要实现的最终目标来说,这可能太复杂了,您可能只需要使用replace,如本例所示:

val config = com.typesafe.config.ConfigFactory.parseString(
  """metrics {
    |  opt_metrics {
    |    query = "select * from opt where created_at='$ds'"
    |  }
    |}
    |""".stripMargin)

val ds = "2022-10-30"

val rawQuery = config.getString("metrics.opt_metrics.query")

rawQuery.replace("$ds", ds) // evaluates to select * from opt where created_at='2022-10-30'

您可以使用这个代码here on Scastie

相关问题