首页 > 解决方案 > 如何从 Cloud Firestore 获取均匀分布的随机文档?

问题描述

这个问题没有提供答案!停止关闭! Firestore:如何在集合中获取随机文档

如果只有两个 idfff...ffe并且fff...fff第一个几乎每次都会被选中,即使按降序排列也是如此。

原帖:

我有一个集合用户,其中 id 是使用 Python 生成的uuid.uuid4(). 我想从集合中选择一个随机 id。如果它可以像 一样安全且“完全均匀”地收集,则可以获得巨大的奖励secrets.choice(),但这并不是完全必要的。

下面是我现在基本上使用的代码。当数据库中有很多文档时,它工作得相当好。

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())

但正如您可以想象的那样,如果没有那么多文档或者文档的 id 几乎彼此相邻,那么它们被选中的机会就会大不相同。

让我们举一个极端的例子。如果只有两个 id fff...ffe 和 fff...fff,那么第一个几乎每次都会被选中。

那么,是否有一种适当的方法可以在不维护所有文档列表或其他一些棘手的解决方法的情况下均匀地选择随机文档?

标签: pythonpython-3.xgoogle-cloud-platformgoogle-cloud-firestore

解决方案


正如问题评论中所讨论的那样-感谢@DougStevenson 和@FrankvanPuffelen 的澄清-在选择随机文档时使用大集合的最佳方法是具有足够熵和均匀分布的字段,然后应用其他中概述的方法问题

如果它是一个小集合,更好的方法是使用某种增量索引,随机选择包含文档的数组。


推荐阅读