Created
January 12, 2018 15:15
-
-
Save dgadiraju/488042e1d94f0772cf742463c279fb10 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ranking - Get top N priced products with in each product category | |
val products = sc.textFile("/public/retail_db/products") | |
val productsMap = products. | |
filter(product => product.split(",")(4) != ""). | |
map(product => (product.split(",")(1).toInt, product)) | |
val productsGroupByCategory = productsMap.groupByKey | |
def getTopNPricedProducts(productsIterable: Iterable[String], topN: Int): Iterable[String] = { | |
val productPrices = productsIterable.map(p => p.split(",")(4).toFloat).toSet | |
val topNPrices = productPrices.toList.sortBy(p => -p).take(topN) | |
val productsSorted = productsIterable.toList.sortBy(product => -product.split(",")(4).toFloat) | |
val minOfTopNPrices = topNPrices.min | |
val topNPricedProducts = productsSorted.takeWhile(product => product.split(",")(4).toFloat >= minOfTopNPrices) | |
topNPricedProducts | |
} | |
val top3PricedProductsPerCategory = productsGroupByCategory.flatMap(rec => getTopNPricedProducts(rec._2, 3)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment