gpt4 book ai didi

android - 获取在 Firestore 中按文档 ID 降序排列的数据

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:21 25 4
gpt4 key购买 nike

我想从我的 Firestore 数据库中获取按 documentId 降序排列的数据。当我打电话时:

firestore.collection("users")
.orderBy(FieldPath.documentId(), Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {...});

我遇到错误:

FAILED_PRECONDITION: The query requires an index.

带有指向 Firebase 控制台的链接以自动创建索引。不幸的是,自动创建在这种情况下似乎不起作用。当我点击创建索引时,我收到一条消息:

__name__ only indexes are not supported

对于手动索引创建,doc仅说明按字段名称(不是 documentId)进行索引。有谁知道如何从 Firestore 获取按 documentId 降序排列的数据?

我知道我可以在客户端重新排序数据,但按 ID 排序是一项很自然的任务,我一定遗漏了一些东西。谢谢你。我使用:

compile 'com.google.firebase:firebase-firestore:11.6.0'

最佳答案

如 Firestore 文档中所述 here , Cloud Firestore 不提供对自动生成的 docID 的自动排序。

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

因此,您可以通过添加额外的字段 createdDate 并使用 annotation 设置它来实现排序@ServerTimestamp,像这样在用户 POJO 的类字段之前声明它。

@ServerTimestamp
Date createdDate;

此外,在将 POJO 写入 Firestore 时,您必须确保此字段为 null,在将其保存到 Firestore 之前不要为其设置任何值。

关于android - 获取在 Firestore 中按文档 ID 降序排列的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47437291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com