英文:
What is the better structure between collection and subcollection in Firestore?
问题
我正在开发一个社交应用,其中有一个“帖子”部分。每个“帖子”可以有“评论”,而每个“评论”可以有“回复”,这些“回复”与类级别的“评论”不同。我正在使用Firebase Firestore
作为后端。正如Firestore
的官方文档所述,有三种方式来组织我们的数据,如下所示:顶级集合、文档和子集合(文档内的集合)。在我的应用中,对于“帖子”,我有一个名为“posts”的顶级集合,其中包含所有“帖子”。现在,每个“帖子”可以有成千上万的“评论”,因此将“评论”存储在每个“帖子”文档中作为映射值不是一个好主意,因为它会超过每个文档的1MB限制,而且添加和删除“评论”会非常困难。所以现在我无法决定是否应该为“评论”创建一个顶级集合,还是在每个“帖子”文档中创建一个子集合。对于每个“评论”的“回复”也是一样的情况。我应该再次为“回复”创建另一个顶级集合,还是在每个“评论”文档中创建一个子集合?我非常感谢您的建议和帮助!
英文:
I am working on a social Flutter
app where there is a section for posts
. Each post
can have comments
and each comment
can have replies
which are different from comment
in class level. I am using Firebase Firestore
as my backend. As the official docs for Firestore
states that there are three ways to structure our data as follows: top-level collection, document and subcollection (collection inside of a document). In my app, for posts
I have a top-level collection called posts
which consists all of the posts
. Now that each post
can have thousands of comments
, so storing comments
inside each post
document as a map value is not a good idea as it will cross the limit of 1MB per document and also adding and deleting a comment
would be so hard. So now I can not decide whether I should create a top-level collection for comments
or a subcollection for comments
in each post
document. It's the same for replies
of each comment
. Should I again create another top-level collection for replies
or a subcollection for replies
in each comment
document? I strongly appreciate your advice and help!
答案1
得分: 1
所以现在我不能决定是否应该创建评论的顶级集合,还是在每篇帖子文档中创建评论的子集合。
从技术或性能的角度来看,两者没有区别,因为:
- Firestore查询性能与结果集的大小成正比,而与数据集的大小无关(即集合中的文档数);
- 您可以使用集合组查询来查询具有相同ID的所有集合中的所有文档(即
comments
或replies
)。
主要区别可能在于Firestore控制台中,您可以轻松显示特定帖子的子集合。
请注意,如果您选择使用根集合来存储comments
或replies
,您不应忘记以一种方式保存父文档的ID,以便可以查询与特定父文档相对应的子文档。
英文:
> So now I can not decide whether I should create a top-level collection
> for comments or a subcollection for comments in each post document.
There is no difference from a technical or performance perspective since:
- A Firestore query performance is proportional to the size of your result set, not your data set (i.e. the number of docs in the collection);
- You can, with Collection Group queries, query all the documents of all collections with the same ID (i.e.
comments
orreplies
).
The main difference is probably that in the Firestore console you can easily display the sub-collection of a specific post.
Note that if you choose to go for root collections for comments
or replies
you should not forget to save the parents IDs in these children docs in such a way you can query the one corresponding to a specific parent.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论