【问题标题】:how to sort data in each partition in spark?如何在火花中对每个分区中的数据进行排序?
【发布时间】:2018-07-26 16:45:20
【问题描述】:

有一些数据:

a   2
b   2
c   2
a   1
c   3
a   3
c   1
b   3
b   1

当我对数据进行重新分区并且没有排序时,代码是:

val sc = new SparkContext
val file = sc.textFile(args(0)).map { a => {
           val splits = a.split("\t")
           (new MyObject(splits(0), splits(1).toInt),"") } }
           .partitionBy(new MyPartitioner(3)) //.sortByKey()    no sort

结果是:

//file:part-00000
(a  2,)
(a  1,)
(a  3,)

//file:part-00001
(b  2,)
(b  3,)
(b  1,)

//file:part-00002
(c  2,)
(c  3,)
(c  1,)

当我对数据进行重新分区并排序时,代码是:

val sc = new SparkContext
val file = sc.textFile(args(0)).map { a => {
           val splits = a.split("\t")
           (new MyObject(splits(0), splits(1).toInt),"") } }
           .partitionBy(new MyPartitioner(3)).sortByKey() 

结果是(不是我想要的,排序后的数据会影响原来的分区):

//file:part-00000
(a  1,)
(a  2,)
(a  3,)
(b  1,)

//file:part-00001
(b  2,)
(b  3,)
(c  1,)

//file:part-00002
(c  2,)
(c  3,)

我期望的结果是:

//file:part-00000
(a  1,)
(a  2,)
(a  3,)

//file:part-00001
(b  1,)
(b  2,)
(b  3,)

//file:part-00002
(c  1,)
(c  2,)
(c  3,)

你能帮帮我吗?非常感谢!

【问题讨论】:

    标签: apache-spark


    【解决方案1】:

    Datasets 的 sortWithinPartitions 函数也可以使用。

    http://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.sql.Dataset

    所以,你可以使用下面的样式

    df.repartition(col("A"), col("B")).sortWithinPartitions(desc("C")) ...
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 2012-12-06
        • 2021-10-23
        • 2021-11-22
        • 1970-01-01
        • 2020-10-05
        • 1970-01-01
        相关资源
        最近更新 更多