firebase-admin
provides a handy, at first glance,
offset
function that allows you to implement pagination in SQL-fashion. If you
are transitioning from PostgreSQL, MySQL, or any other traditional
database, it might seem more natural than
Firestore's query cursors.
But that's the Trojan Horse. Because of the way how Firestore indexes works, such code will produce 2900 document reads and take 10s (given your document has just one field, on real data this query might take minutes to finish):
import * as admin from 'firebase-admin'
admin.initializeApp()
admin
.firestore()
.collection('pages')
.orderBy('number')
.limit(1)
.offset(2900)
.get()
It easy to verify using the Firestore's usage tab:
As you can see, after running this code, the number of reads grew from
4.5K
to 7.4K
.
Never use the offset
function. Otherwise, you'll end up with
a very slow and expensive code. Learn how to use query cursors instead.
Besides being snappy fast, it will provide better UX as the same page will
always produce the same results, unlike pagination by offset where items
constantly shift.