首页 > 解决方案 > 如何使用 SparkR 在 Spark SQL 中传递变量?

问题描述

我是 SparkR 的新手。我正在尝试使用 Qubole Notebook 使用 SparkR 在数据集上编写查询。采取了几个过程但没有得到输出。

数据:表_A

ID      Name     month      year
1        A         2        2020
2        B         2        2019
3        c        12        2019

期望的输出:

ID      Name     month      year
1        A         2        2020

在此处输入图像描述

变量:

month_value= 2
year_value = 2020

过程1:

temp_data = sql("
select * 
from Table_A
where month = $month_value and year = $year_value")

过程2:

temp_data = sql(s"
select * 
from Table_A
where month = $month_value and year = $year_value")

过程3:

temp_data = sql("
select * 
from Table_A
where month = {0} and year = {1}".format(month_value,year_value))

过程4:

temp_data = sql("
select * 
from Table_A
where month = ${month_value} and year = ${year_value}")

如何使用 SparkR 在 Spark SQL 中传递变量?

标签: sqlvariablessparkr

解决方案


过滤可以使用函数中的子句wheresql直接使用filter函数来完成。

使用样本数据进行设置:

library(SparkR, lib.loc = c(file.path(Sys.getenv("SPARK_HOME"), "R", "lib")))
sparkR.session(master = "local[*]", sparkConfig = list(spark.driver.memory = "8g"))

local_df <- data.frame(ID=c(1, 2 ,3),
                       Name=c("A", "B", "c"),
                       month=c(2, 2, 12), 
                       year=c(2020, 2019, 2019))

month_value <- 2
year_value <- 2020

sdf <- createDataFrame(local_df)

第一种方法使用sql. 从名为 的 SparkDataFrame 创建临时视图sdf。然后就可以用它glue来编写 sql 代码了。它是一个比使用更干净的字符串插值器paste

# 1) SQL function (string interpolation)
createOrReplaceTempView(sdf, "Table_A")
(sql_expanded <- as.character(glue::glue(
  "select * from Table_A where (month == {month_value}) and (year == {year_value})")))
head(sql(sql_expanded))

结果:

> (sql_expanded <- glue::glue(
+   "select * from Table_A where (month == {month_value}) and (year == {year_value})"))
select * from Table_A where (month == 2) and (year == 2020)
> head(sql(as.character(sql_expanded)))
  ID Name month year
1  1    A     2 2020

第二个选项,使用filter

> head(filter(sdf, sdf$month == month_value & sdf$year == year_value))
  ID Name month year
1  1    A     2 2020

推荐阅读