Random row in Scala Slick 3.0 -
how 1 random row out of table efficiently?
what have far (doesn't compile , misguided):
val query = { m <- tablequery maxid <- tablequery.groupby(_.id).map { case (tid, t) => t.map(_.id).max}//m.map(_.id).max if (m.id >= maxid * random.nextfloat()) } yield m edit: after tinkering , of bhavya i've come following code job makes 2 database roundtrips:
val maxidquery: rep[option[int]] = magiccarddumps.map(_.id).max val maxidfuture: future[option[int]] = db.run(maxidquery.result) val maxid = await.result(maxidfuture, 10 seconds).get val randcardquery: query[magiccarddumps, magiccarddump, seq] = magiccarddumps.filter(_.id >= (maxid * random.nextfloat()).toint).sortby(_.id).take(1) val resultfuture: future[seq[magiccarddump]] = db.run(randcardquery.result) val resultseq: seq[magiccarddump]= await.result(resultfuture, duration(10, "seconds")) val card = resultseq.head println(card) how can these queries merged 1 , made more efficient?
the best way use simplefuction
val rand = simplefunction.nullary[double]("rand") query.sortby(x => rand).take(1) works in postgres , mysql
Comments
Post a Comment