Is there any standard firestore query to get random documents?

早过忘川 提交于 2021-01-29 07:40:36

问题


I am trying to get multiple random documents from a dynamic collection. Until know, I have thought to do it using simple queries, something like this:

 Pseudocode
 
 arr = [];
 while (arr.length < 5) {
     // Start the query at a random position
     startAt = Math.random() * collection.size;
     randomDoc = await dbRef.startAt(startAt).limit(1).get( ... );
     arr.push(randomDoc);
 }

Here, firstly, I have to get the collection size, as it can be 0 or bigger. Then, select a random document using a kind of "db random pointer/index".

My question is if there is any way to get the same result but without all the loop stuff, only with the query syntax.

Thank you.


回答1:


Clever use of startAt and limit!
As you can see in the reference, there are no built-in methods that would return random documents.

In order to avoid the loop, you can use Promise.all:

const indices = getRandomIndices(collection.size);
const docs = await Promise.all(indices.map(i => {
    return dbRef.startAt(i).limit(1).get();
}));

And for the getRandomIndices, I suggest: create an array [0, 1, 2, ...], shuffle it as describe in this SO answer, and slice its 5 first elements.



来源:https://stackoverflow.com/questions/64183659/is-there-any-standard-firestore-query-to-get-random-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!