如何使用python在spark SQL中传递变量?

Viv*_*Viv 8 python apache-spark apache-spark-sql pyspark

我在python中编写spark代码.如何在spark.sql查询中传递变量?

    q25 = 500
    Q1 = spark.sql("SELECT col1 from table where col2>500 limit $q25 , 1")
Run Code Online (Sandbox Code Playgroud)

目前上面的代码不起作用?我们如何传递变量?

我也尝试过,

    Q1 = spark.sql("SELECT col1 from table where col2>500 limit q25='{}' , 1".format(q25))
Run Code Online (Sandbox Code Playgroud)

Lui*_*ola 9

使用 f 字符串方法 (PySpark):

table = 'my_schema.my_table'

df = spark.sql(f'select * from {table}')
Run Code Online (Sandbox Code Playgroud)


Tin*_*y.D 8

您需要删除单引号和q25字符串格式,如下所示:

Q1 = spark.sql("SELECT col1 from table where col2>500 limit {}, 1".format(q25))
Run Code Online (Sandbox Code Playgroud)

更新:

根据您的新查询:

spark.sql("SELECT col1 from table where col2>500 order by col1 desc limit {}, 1".format(q25))
Run Code Online (Sandbox Code Playgroud)

请注意,SparkSQL不支持OFFSET,因此查询无法正常工作.

如果您需要添加多个变量,可以尝试这种方式:

q25 = 500
var2 = 50
Q1 = spark.sql("SELECT col1 from table where col2>{0} limit {1}".format(var2,q25))
Run Code Online (Sandbox Code Playgroud)


Dav*_*dox 5

如果您经常执行此类操作或希望使代码更易于重用,另一种选择是使用配置变量映射和格式选项:

configs = {"q25":10,
           "TABLE_NAME":"my_table",
           "SCHEMA":"my_schema"}
Q1 = spark.sql("""SELECT col1 from {SCHEMA}.{TABLE_NAME} 
                  where col2>500 
                  limit {q25}
               """.format(**configs))
Run Code Online (Sandbox Code Playgroud)