Skip to content

Instantly share code, notes, and snippets.

@johnykov
Last active July 13, 2017 17:49
Show Gist options
  • Save johnykov/7d2d533fc2dfea72097325334df94eb2 to your computer and use it in GitHub Desktop.
Save johnykov/7d2d533fc2dfea72097325334df94eb2 to your computer and use it in GitHub Desktop.
My non-blocking scala recommender, searching through database for cheaper merchant, scala, slick
class Recommender(transactionModel: SasquatchTransactionModel)(implicit ec: ExecutionContext) extends StrictLogging {
def findCheaperMerchant(transaction: SasquatchTransactionDTO): DBRead[Seq[SasquatchRecommendation]] = {
val mId: String = transaction.merchantId
logger.info(s"Computing cheaper merchant for transaction: ${transaction.extId} merchant: ${mId}")
val top10NearestMerchants = transactionModel.nearestNeighbour(
long = transaction.long,
lat = transaction.lat,
category = transaction.category
)
val isCheaper: (SasquatchTransaction) => Boolean = _.amount.abs < transaction.amount.abs
val notSelf: (SasquatchTransaction) => Boolean = _.merchantId != mId
top10NearestMerchants.flatMap(nearMerchants => {
def getDistance(merchantId: String) = nearMerchants.filter(_.id == merchantId).map(_.distance).headOption
logger.info(s"Found near Merchants: ${nearMerchants.filter(_.id != mId).map(_.id)}")
transactionModel.findByMerchantDistanceInSet(nearMerchants)
.map(_.filter(isCheaper)
.filter(notSelf).flatMap(recommendedTransaction =>
for {
mmId <- recommendedTransaction.merchantId
dist <- getDistance(mId)
} yield SasquatchRecommendation(mId, mmId, dist)))
})
}
}
case class SasquatchTransactionDTO(extId: String, merchantId: String, category: String, long: Float, lat: Float, amount: BigDecimal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment