DEV Community

yuyu
yuyu

Posted on

Get Random Documents from Firestore

When working with Firestore, retrieving random elements poses a challenge because Firestore does not natively support queries for fetching documents randomly.

In addition, Firestore does not support offset queries, so it is not possible to generate a random number on the client side and then fetch documents randomly by specifying an index.

Basic Solution

  • Fetch all documents in the collection, shuffle the array, and then select elements either from the beginning or at random indexes.

This method is quite simple. However, if there are a large number of documents, it can be quite costly and the processing speed may become slow.

Another Approach: Changing the Way to Manage Data

This is a solution that only loads the necessary records.

  1. Configure a property within each document that has a number assigned randomly.
  2. When fetching documents, use an orderBy query targeting this random number property. By combining this with a limit query, it is possible to fetch a specified number of documents or even the entire collection.
  3. After fetching the documents, assign a new random number to the random number property of each document. This step ensures that the collection remains shuffled reproducibly.

firestore console

Bottleneck

This method requires a significant number of write operations. Since Firestore incurs higher costs for write operations compared to read or delete operations, frequent fetching can become costly.

See also: https://firebase.google.com/docs/firestore/pricing

Finally

I was pleasantly surprised when I first discovered this method. Despite Firestore not supplying direct queries for fetching random documents, this creative solution offers an excellent workaround.

Top comments (0)