How would I write a findRandom entries Controller?

Hey everyone,

I’ve recently written a custom Controller that returns me “pseudorandom” entries like this:

    module.exports = {
      // GET /things/random
      async findRandom(ctx) {
        let entities;
        if (ctx.query._q) {
          entities = await strapi.services.thing.search(ctx.query);
        } else {
          entities = await strapi.services.thing.find(ctx.query);
        }

        const entitiesLength = entities.length;

        entities = getRandom(entities, entitiesLength >= 24 ? 24 : entitiesLength);

        return entities.map((entity) =>
          sanitizeEntity(entity, { model: strapi.models.thing })
        );
      },
    };

where the getRandom() function takes the array and a number of elements I want.

How would I actually do a randomized query to the Postgres DB though? Because if I SELECT everything from the db and then do my getRandom() function in a Strapi Controller it will be very very slow. I have over 5000 entries that contain images.

Hope someone has an idea, thanks

System Information
  • Strapi Version: latest
  • Operating System: Ubuntu 20
  • Database: Postgres
  • Node Version: 14
  • NPM Version: 6

That is a good one, you would need an index of all of the existing IDs then perform some kind of function to pick one at random :thinking: Many SQL databases (not sure on MongoDB) support a random “order by” so you could logically use our custom queries: https://strapi.io/documentation/developer-docs/latest/concepts/queries.html#bookshelf

And do something like what is described in this article: MySQL Select Random Records