If you just want to randomly sort results within a request, you can use this plugin:
If you want to take a random sample from the whole collection I’d recommend combining raw SQL query (to tap into the random ordering capabilities of your DB) and the Entity Service (to leverage the Strapi’s handling of relations, components etc.) Something along the lines of:
const uid = "api::<name>.<content-type>";
const ids = (
await strapi.db.connection
.select("id")
.from(strapi.getModel(uid).collectionName)
// The random function of your DB. This one is Postgres'.
.orderByRaw("RANDOM()")
// Your desired number of samples.
.limit(10)
).map(it => it.id)
const samples = await strapi.entityService.findMany(uid, {
filters: {
id: {
$in: ids
}
}
})
Note that this approach doesn’t play well with pagination - you couldn’t avoid duplicate entries across page requests. Doing that is quite more complicated.