字符串插值问题 Jupyter Notebook Pyspark

问题描述 投票:0回答:1

我将以下内容作为查询 (.dbtable) 传递给 pyspark,在 AWS EMR 上的 jupyter 笔记本中运行。

num = [1234,5678]

newquery = "(SELECT * FROM db.table WHERE col = 1234) as new_table"
newquery = "(SELECT * FROM db.table WHERE col = {num}) as new_table"
newquery = "(SELECT * FROM db.table WHERE col IN %(num)s) as new_table"
newquery = "(SELECT * FROM db.table WHERE col IN :(num)) as new_table"

第一个“newquery”将返回结果。其余的都失败了。

退货的正确方法是什么?

apache-spark pyspark string-interpolation
1个回答
0
投票

您可以尝试在 PySpark 中使用 f 字符串

num = [1234,5678]

filter_part = str(num)[1:-1]

newquery = f"(SELECT * FROM db.table WHERE col IN ({num_str})) AS new_table"

# Run the query
spark.sql(newquery)

另请注意,此函数

str(num)[1:-1]
对于字符串输入也是安全的,如果您的列表具有像
['1234', '5678']
这样的字符串,它应该创建一个
IN
子句来将其考虑在内。

我也希望您使用

new_table
作为子查询的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.