gpt4 book ai didi

java - Firebase 数据库 - "Fan Out"技术

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:46 25 4
gpt4 key购买 nike

我正在调查 Firebase 数据库 sample对于安卓并意识到它以下列方式存储其数据:

enter image description here

我不太熟悉 NoSQL 技术并试图理解为什么我们必须坚持每个 post实体两次 - 在 postsuser_posts相应地。文档说这种方法称为“扇出”,我完全同意通过像 databaseReference.child("user-posts").child("<user_uid>") 这样的简单构造来访问用户的帖子可能很有用。 .但是为什么我们需要 posts节点呢?如果我们需要更新一些帖子怎么办 - 我们必须更新两次吗?

// [START write_fan_out]
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();

Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

mDatabase.updateChildren(childUpdates);
}
// [END write_fan_out]

所以我想知道...这种方法何时有用,何时无用? Firebase SDK 是否提供任何工具来在更新或删除数据时使所有重复项保持同步?


更新:这是解释 received来自 Firebase 团队:

the reason the posts are duplicated is because we want to be able to quickly get all the posts belonging to a user (as you suggested) and filtering from the list of all posts ever to get the posts by one user can get pretty expensive as the number of posts expands.

This does mean that we have to update the post in two locations whenever we update it. It makes the code a little uglier but since queries are more common than writes it's better to optimize for reading the data.

我怀疑这种方法可能看起来不太优雅,但它可能是大型数据集的最快选择,只要您执行 SELECT 的频率高于 UPDATE。但是,在某些情况下,我宁愿坚持使用此处推荐的其他解决方案。

最佳答案

数据扇出是一种管理大量数据的好方法。如果不使用此模式,将来可能会遇到严重的缩放问题。

我从您的数据库结构中看到,您将整个帖子信息存储两次,这不是一个好的做法。您希望在另一个节点下存储只是对帖子的引用。因此,您将有一个名为 users-posts 的节点,它将包含用户键,并且每个键都有一组值为 true 的帖子键。为了更清楚:

enter image description here

这样,您就可以跟踪用户在 users-posts 节点下写了哪些帖子;以及在 posts 节点下撰写每篇文章的用户。现在,您可能需要获取所有用户帖子的列表。您需要做的是在 users-posts/USER_KEY/ 节点上同步以获取用户已写的所有帖子的 key ,然后获取更多发布信息使用您刚刚获得的发布 key

为什么推荐这种数据库设计?因为您每次同步获得的信息少得多(对于 Firebase,我们本身不发出请求,因此我将读取称为同步)。在您的示例中,如果您将监听器附加到 user-posts/USER_KEY/ 以获取所有帖子的列表,您还将要求ALL 的信息>每一个他们写的帖子。使用数据扇出方法,您可以只询问您需要的帖子信息,因为您已经拥有帖子的 key 。

关于java - Firebase 数据库 - "Fan Out"技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38181973/

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