SparkのsortByとsortByKey



Spark Sortby Sortbykey



多くのアプリケーションシナリオでは、結果データを並べ替える必要があります。 スパーク 中国も例外ではありません。に スパーク RDDの並べ替えには、sortBy関数とsortByKey関数の2つの関数があります。 sortByは、Spark 0.9.0の後に導入された標準RDDをソートするためのものです(SPARK-1063を参照)。 sortByKey関数は、キーと値を持つRDDであるPairRDDをソートすることです。これら2つの機能の実装と使用法を以下に説明します。

sortBy関数

情報源:



hello you hello me hello you

キュースケール:

object SparkWordCount { def main(args: Array[String]): Unit = { //spark execution entrance val sc = new SparkContext(new SparkConf().setMaster('local').setAppName('SparkWordCount')) //Read the data source, create an RDD val lines: RDD[String] = sc.textFile('E:\wordcount.txt') //flatMap: Divide and flatten according to the spaces, break them into one and combine them into one object. map: Combine words and 1 to form a tuple val data: RDD[(String, Int)] = lines.flatMap(_.split(' ')).map(x=>(x,1)) //Aggregate by key, add the same key and value val value: RDD[(String, Int)] = data.reduceByKey((x, y)=>x+y) //sortBy: sort by value, sort in descending order val value1: RDD[(String, Int)] = value.sortBy(_._2,false) val buffer = value1.collect().toBuffer println(buffer) sc.stop() } }

演算結果:



sortByKey関数:

情報源:

hello you hello me head you hard me main yarn

キュースケール:



object SparkWordCount { def main(args: Array[String]): Unit = { //spark execution entrance val sc = new SparkContext(new SparkConf().setMaster('local').setAppName('SparkWordCount')) //Read the data source, create an RDD val lines: RDD[String] = sc.textFile('E:\wordcount.txt') //flatMap: Divide and flatten according to the spaces, break them into one and combine them into one object. map: Combine words and 1 to form a tuple val data: RDD[(String, Int)] = lines.flatMap(_.split(' ')).map(x=>(x,1)) //Aggregate by key, add the same key and value val value: RDD[(String, Int)] = data.reduceByKey((x, y)=>x+y) //sortByKey Sorting method: sort according to the alphabetical order of the words that can be sorted in descending order val value1: RDD[(String, Int)] = value.sortByKey(false) val buffer = value1.collect().toBuffer println(buffer) sc.stop() } }

結果:

注:コード内のsortByKeyは、アルファベット順に並べ替えられたキーで並べ替えられます