[英]Filter Spark Dataframe with a variable
這甚至可能在火花數據幀(1.6/2.1)中
val data="some variable"
df.filter("column1"> data)
我可以用靜態值來做到這一點,但無法弄清楚如何通過變量進行過濾。
import org.apache.spark.sql.functions._
val data="some variable"
df.filter(col("column1") > lit(data))
我不確定你是如何用文字完成的,因為你所擁有的與任何filter
方法簽名都不匹配。
所以是的,你可以使用非文字,但試試這個:
import sparkSession.implicits._
df.filter($"column1" > data)
請注意$
,它使用implicit
轉換將String
轉換為以該String
命名的Column
。 同時,這個Column
有一個>
方法,它接受一個Any
並返回一個新的Column
。 Any
將是您的data
值。
在 Java 中,我們可以這樣做:
int i =10;
//for equal condition
df.select("column1","column2").filter(functions.col("column1").equalTo(i)).show();
//for greater than or less than
df.select("no","name").filter(functions.col("no").gt(i)).show();
df.select("no","name").filter(functions.col("no").lt(i)).show();
是的,您可以使用變量來過濾 Spark Dataframe。
val keyword = "my_key_word"
var keyword = "my_key_word" // if it is a variable
df.filter($"column1".contains(keyword))
df.filter(lower($"column1").contains(keyword)) //if not case sensitive
這是在數字列上使用<
>
=
的過濾器的完整演示,其中mysearchid
是在下面聲明為val
的數字...
scala>val numRows =10
scala>val ds = spark.range(0, numRows)
ds: org.apache.spark.sql.Dataset[Long] = [id: bigint]
scala>val df = ds.toDF("index")
df: org.apache.spark.sql.DataFrame = [index: bigint]
scala>df.show
+-----+
|index|
+-----+
| 0|
| 1|
| 2|
| 3|
| 4|
| 5|
| 6|
| 7|
| 8|
| 9|
+-----+
scala>val mysearchid=9
mysearchid: Int = 9
scala>println("filter with less than ")
filter with less than
scala>df.filter(df("index") < mysearchid).show
+-----+
|index|
+-----+
| 0|
| 1|
| 2|
| 3|
| 4|
| 5|
| 6|
| 7|
| 8|
+-----+
scala> println("filter with greater than ")
filter with greater than
scala> df.filter(df("index") > mysearchid).show
+-----+
|index|
+-----+
+-----+
scala> println("filter with equals ")
filter with equals
scala> df.filter(df("index") === mysearchid).show
+-----+
|index|
+-----+
| 9|
+-----+
你可以簡單地使用字符串插值來做到這一點
val data="some variable"
df.filter(s"column1 > $data")
import org.apache.spark.sql.functions._
val portfolio_name = "Product"
spark.sql("""SELECT
*
FROM
Test""").filter($"portfolio_name"===s"$portfolio_name").show(100)
val x = "2020-05-01"
df.filter($"column_name"===x).show()
如果您想將變量與整列進行比較,它將起作用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.