Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Spark DataFrame by checking if value is in a list, with other criteria

As a simplified example, I tried to filter a Spark DataFrame with following code:

val xdf = sqlContext.createDataFrame(Seq(
  ("A", 1), ("B", 2), ("C", 3)
)).toDF("name", "cnt")
xdf.filter($"cnt" >1 || $"name" isin ("A","B")).show()

Then it errors:

org.apache.spark.sql.AnalysisException: cannot resolve '((cnt > 1) || name)' due to data type mismatch: differing types in '((cnt > 1) || name)' (boolean and string).;

What's the right way to do it? It seems to me that it stops reading after name column. Is it a bug in the parser? I'm using Spark 1.5.1

like image 239
Bamqf Avatar asked Nov 29 '15 09:11

Bamqf


2 Answers

val list = List("x","y","t") 
xdf.filter($"column".isin(list: _*))
like image 175
pschilakanti Avatar answered Nov 12 '22 18:11

pschilakanti


You have to parenthesize individual expressions:

xdf.filter(($"cnt" > 1) || ($"name" isin ("A","B"))).show()
like image 44
zero323 Avatar answered Nov 12 '22 18:11

zero323