2016-03-23 11 views
0

私はApache Sparkを使って計算しています。私はこのようなクエリを実行します。sparkにforeachGroupメソッドのような関数がありますか?

SELECT country, school, subjects, avg(score) FROM table GROUP BY country,school,subject 

だから、結果は以下のようである:

USA, school1, math, 99 
USA, school1, sport, 98 
USA, school2, math, 90 
ENG, school1, science, 100 

今(国+ school_idによって表される)各学校のために、我々は彼らのスコアに基づいて上位3件名を取得する必要があります。

私はこれを行う2つの方法を考えています。

1. If there is some method called foreachGROUP, Then I will run code like 

result.foreachGROUP(get_top_3) 


2. I know there is a method called repartion. Then I guess I can do something like : 

result.repartion(country,school) # repartion by country and school 
foreachPartion(get_top_3) 

私はApache sparkに精通していません。どのような方法が可能かどうかは分かりません。親切に助言をお願いします。あなたはこれよりも良い方法があれば。あなたは、テストデータを設定するとも

答えて

0

をadivceてください:

val df = sc.parallelize(Array(
    Rec("USA","school1", "math", 98.0), 
    Rec("USA","school1", "lit", 96.0), 
    Rec("USA","school1", "trig", 92.0), 
    Rec("USA","school1", "eng", 94.0) 
)).toDF 

あなたはgroupBy()、wtih collect_list()、その後explodeトップ3の操作を行います。

val top3bySchool = df.groupBy($"country", $"school") 
    .agg(collect_list($"subject") as "subjectList", collect_list($"score") as "scoreList") 
    .explode($"subjectList", $"scoreList"){r => { 
    val subjectList = r.getSeq[String](0).zip(r.getSeq[Double](1)).sortWith((a,b) => { 
     a._2 > b._2 
    }); 
    subjectList.slice(0, if (subjectList.length < 3) subjectList.length else 3); 
    }}.select($"country",$"school",$"_1" as "subject", $"_2" as "score") 
+0

おかげでデビッド。あなたはスカラやJAVAを使っていますか?なぜなら私はこれら2つのことに慣れていないからです。私はPythonを使用しています。あなたはPythonでいくつかの例を提供できますか? –

関連する問題