如何根据标准从RDD中的一系列记录中获取记录集?

时间:2017-02-15 17:48:35

标签: scala apache-spark

我是Spark的新手,我正在努力解决以下火花问题。我有一个包含大量记录的表。表包含student_id,course_id,risk_date,first_name,last_name。根据业务场景,一个student_id和course_id可能有多个risk_dates。因此,我需要使用最新的risk_date获取特定student_id和course_id的student_id,course_id,risk_date。

如果我在SQL查询中提到我的scanario就像

select student_id, course_id, max(risk_date) from
students group by  student_id, course_id

我的Scala代码如下所示。

val sqlCaller = sparkSession.read.format("jdbc")
  .option("driver", "com.mysql.jdbc.Driver")
  .option("url", url)
  .option("dbtable", "student_risk")
  .option("user", "dmin")
  .option("password", "admin123")
  .load()
sqlCaller.cache();

val studentRDD = sqlCaller.rdd.map(r => (r.getString(r.fieldIndex("course_id")), r.getString(r.fieldIndex("student_id")), r.getTimestamp(r.fieldIndex("risk_date"))))

我可以使用过滤器吗?我不想使用SQL语句来获取符合我要求的数据。有人可以帮我这么做吗?

1 个答案:

答案 0 :(得分:0)

你可以尝试这个(更新):

import org.apache.spark.sql.SparkSession

val spark = SparkSession
  .builder()
  .getOrCreate()

import spark.implicits._

val df = Seq(
  (1, 1, "2017-01-01"),
  (1, 1, "2017-01-02"),
  (1, 2, "2017-01-04"),
  (1, 2, "2017-01-05"),
  (2, 1, "2017-01-01")
).toDF("student_id", "course_id", "risk_date")

df.groupBy($"student_id", $"course_id").agg(max("risk_date")).show