THIS QUESTION DOESNT PROVIDE AN ANSWER! STOP CLOSING! Firestore: How to get random documents in a collection
If there were only two ids fff...ffe
and fff...fff
the first one would get picked practically every time even with that descending order.
Original post:
I have a collection users, where ids are generated with Python's uuid.uuid4()
. I'd like to pick a random id from the collection. Huge bonus if it can be securely and "perfectly evenly" gathered like secrets.choice()
, but that isn't completely necessary.
Below is the code I'm basically using now. It works reasonably well, when there's lots of documents in the database.
from uuid import uuid4
from google.cloud import firestore_v1 as firestore
client = firestore.Client()
def get_random_user_id():
"""Try to find a random user id."""
search_id = str(uuid4())
print('searhing from: {}'.format(search_id))
query = client.collection('users').where(
firestore.field_path.FieldPath.document_id(),
'>=',
client.document('users/' + search_id)
).limit(1)
docs = query.stream()
for doc in docs:
return doc.id
# Maybe there aren't that many documents, just get the first document
docs = client.collection('users').limit(1).stream()
for doc in docs:
return doc.id
# No documents found
return False
print(get_random_user_id())
But as you can imagine, if there aren't that many documents or the documents have ids that are almost right next to each other, the chances for them to be picked are quite different.
Lets's have an extreme example. If there were only two ids fff...ffe and fff...fff the first one would get picked practically every time.
So, is there a proper way to pick random documents evenly without maintaining a list of all documents or some other hacky workaround?