How to get random recrods from findMany? #5886
|
As discussed in Prisma 1 forum, I'd like to know how to find random records in The below query should work in |
Replies: 17 comments 33 replies
|
Hey @hyochan, thanks a lot for raising this! I don't think returning items from Alternatively, you can of course use the SQL query that you posted above and send it to the DB using Prisma Client's In any case, I think this is a really interesting feature request, would you mind persisting it in a GitHub issue so that our Product and Engineering teams can look into it? |
|
Try something like this const productsCount = await prisma.product.count();
const skip = Math.floor(Math.random() * productsCount);
return await prisma.product.findMany({
take: 5,
skip: skip,
orderBy: {
sellingCount: 'desc',
},
}); |
|
My current attempt: async pickRandom(count: number): Promise<CognitiveTest[]>{
const itemCount = await this.prisma.cognitiveTest.count();
const skip = Math.max(0, Math.floor(Math.random() * itemCount) - count);
const orderBy = randomPick(['id', 'field1', 'field2']);
const orderDir = randomPick([SortOrder.asc, SortOrder.desc]);
return this.prisma.cognitiveTest.findMany({
take: count,
skip: skip,
orderBy: { [orderBy]: orderDir },
});
} |
|
Yet another problem, that could be easily solved by allowing raw sql in Prisma API. See #5560 If raw sql would be allowed in Prisma API, the solution to this problem could look like this: prisma.users.findMany({
orderBy: raw`random()`,
take: 1
}); |
|
I wait the issue to be completed but if you need a temporary solution : |
|
To simplify all the above: results = await prisma.$queryRawUnsafe(
// DO NOT pass in or accept user input here
`SELECT * FROM "Post" ORDER BY RANDOM() LIMIT 30;`,
) |
|
For MySQL or PlanetScale, a sample code: return await prisma.$queryRaw`SELECT * FROM accounts WHERE is_public = 1 ${
adminId ? Prisma.sql`AND admin_id <> ${adminId}` : Prisma.empty
} ORDER BY RAND() LIMIT 3`; |
|
+1. |
|
With the new Views feature in Prisma you could create a view with and then create a view model in your Prisma schema that mirrors your user model. |
|
things to keep in mind: Using Can be an issue with large tables |
|
This comment was marked as disruptive content.
This comment was marked as disruptive content.
function getRandomGifts() {
const allIds = await this.databaseService.gift.findMany({
select: {
id: true,
},
})
allIds.sort(() => Math.random() - 0.5)
const randomIds = allIds.slice(0, 20).map((gift) => gift.id)
return await this.databaseService.gift.findMany({
where: { id: { in: randomIds } },
})
} |
|
Prisma still doesn't support this yet lol Why should everyone suffer by not providing About 3 years have passed, but nothing has changed. This isn't even a special feature. It is used by many developers. I really wonder that the Prisma development team consider some useful tools for web developer. |
|
|
In case you don't want to dabble yourself with raw SQL and need the type appropriately: const users = await prisma.user.count()
const foundUsers = await prisma.user.findMany({
take: 10,
skip: Math.floor(Math.random() * (users - 10)),
})Just note, this doesn't randomize every pick and just the interval to start from. |
|
Please prioritize this. A simple |
Hey @hyochan, thanks a lot for raising this! I don't think returning items from
findManyin a random order is natively supported by Prisma Client yet and I don't think there's another way how you could retrieve a random element with Prisma Client. If you only care about getting a single item though and not really about the randomness, you can usefindFirst.Alternatively, you can of course use the SQL query that you posted above and send it to the DB using Prisma Client's
$queryRawmethod.In any case, I think this is a really interesting feature request, would you mind persisting it in a GitHub issue so that our Product and Engineering teams can look into it?