34

What's the syntax for using a groupby-having in Spark without an sql/hiveContext? I know I can do

DataFrame df = some_df
df.registreTempTable("df");    
df1 = sqlContext.sql("SELECT * FROM df GROUP BY col1 HAVING some stuff")

but how do I do it with a syntax like

df.select(df.col("*")).groupBy(df.col("col1")).having("some stuff")

This .having() does not seem to exist.

zero323
  • 322,348
  • 103
  • 959
  • 935
lte__
  • 7,175
  • 25
  • 74
  • 131

2 Answers2

52

Yes, it doesn't exist. You express the same logic with agg followed by where:

df.groupBy(someExpr).agg(somAgg).where(somePredicate) 
zero323
  • 322,348
  • 103
  • 959
  • 935
27

Say for example if I want to find products in each category, having fees less than 3200 and their count must not be less than 10:

  • SQL query:
sqlContext.sql("select Category,count(*) as 
count from hadoopexam where HadoopExamFee<3200  
group by Category having count>10")
  • DataFrames API (Pyspark)
from pyspark.sql.functions import *

df.filter(df.HadoopExamFee<3200)
  .groupBy('Category')
  .agg(count('Category').alias('count'))
  .filter(col('count')>10)
Community
  • 1
  • 1
Karthik
  • 1,143
  • 7
  • 12