197、Spark 2.0之Dataset开发详解-聚合函数:avg、sum、max、min、count、countDistinct

代码

object AggregateFunction {

  case class Employee(name: String, age: Long, depId: Long, gender: String, salary: Long)

  case class Department(id: Long, name: String)

  def main(args: Array[String]): Unit = {
    val sparkSession = SparkSession
      .builder()
      .appName("AggregateFunction")
      .master("local")
      .getOrCreate()

    import sparkSession.implicits._
    import org.apache.spark.sql.functions._

    val employeePath = this.getClass.getClassLoader.getResource("employee.json").getPath
    val departmentPath = this.getClass.getClassLoader.getResource("department.json").getPath

    val employeeDF = sparkSession.read.json(employeePath)
    val departmentDF = sparkSession.read.json(departmentPath)

    val employeeDS = employeeDF.as[Employee]
    val departmentDS = departmentDF.as[Department]

    employeeDS
      .join(departmentDS, $"depId" === $"id")
      .groupBy(departmentDS("name"))
      .agg(avg(employeeDS("salary")), sum(employeeDS("salary")), max(employeeDS("salary")), min(employeeDS("salary")), count(employeeDS("name")), countDistinct(employeeDS("name")))
      .show()
  }
}

你可能感兴趣的:(197、Spark 2.0之Dataset开发详解-聚合函数:avg、sum、max、min、count、countDistinct)