有没有办法优化Scala中连接的RDD的分组?

时间:2018-04-06 12:27:17

标签: scala apache-spark rdd

我刚开始学习Scala和Spark,这是我尝试加入促销商品和汽车的方法。 Sale items代表有关汽车销售的信息(carId,saleDate,cityofSale,price)。 Cars只是一个带有汽车信息的元组(carId,carName)。 ReportItem是最终报告(carId,carName,saleDate,cityofSale,price)。

该方法返回预期结果:ReportItems,其具有给定carId / saleDate的最高价格。 作为Scala / Spark的初学者,我可能错过了一些东西,所以我想提出建议。有没有办法从Scala机会点更优化地实现该方法。我有一个想法,使用reduceByKey()方法。但是找不到在方法中正确实现它的方法。我会对任何建议和批评表示感谢。

    def getSales(sales: RDD[SaleItem], cars: RDD[(String, String)]): RDD[ReportItem] = {
        val mappedSales = sales.keyBy(_.carId)
        val mappedCars = cars.keyBy(_._1)
        mappedSales.join(mappedCars)
          .map({
            case (_, (saleItem, car)) => ReportItem(saleItem.carId, car._2, saleItem.saleDate, saleItem.city, saleItem.price)
          })
          .map(reportItem => ((reportItem.carId, reportItem.saleDate), reportItem))
          .groupByKey()
          .map({ case ((id, date), reportItem) => reportItem.maxBy(_.price) })
}

1 个答案:

答案 0 :(得分:2)

是的,可以使用int split( char* str, char*** arr ) { int arrsz = 0 ; char delim[2] = ":" ; char* tok ; *arr = malloc(sizeof(char**)); *arr[0] = malloc(1); **arr[0] = '\0'; // <<< This is fixed too tok = strtok( str, delim ) ; while( tok != NULL ) { arrsz++; *arr = (char **)realloc(*arr,(arrsz*sizeof(char *))+1); *arr[arrsz-1] = malloc((sizeof(char)*strlen(tok))+1); strcpy(*arr[arrsz-1],tok); *arr[arrsz]=malloc(1); *arr[arrsz]='\0'; tok = strtok(NULL,delim); } return(arrsz); }

对其进行优化
.reduceByKey()

这样效率更高,因为我们只为给定的def getSales(sales: RDD[SaleItem], cars: RDD[(String, String)]): RDD[ReportItem] = { val mappedSales = sales.keyBy(_.carId) val mappedCars = cars.keyBy(_._1) mappedSales.join(mappedCars) .map({ case (_, (saleItem, car)) => ReportItem(saleItem.carId, car._2, saleItem.saleDate, saleItem.city, saleItem.price) }) .map(reportItem => ((reportItem.carId, reportItem.saleDate), reportItem)) .reduceByKey((item1, item2) => if(item1.price > item2.price) item1 else item2) //item1 & item2 are of type: ReportItem .values } 对保留一个ReportItem,因为最高价格的(carId, saleDate)已经解决了。对于内存中的给定对,代码中的ReportItem保留所有groupBy的{​​{1}},并在结束时计算最大值,这是一个严重的内存耗尽,尤其是在数据偏斜的情况下。