我正在调查针对Android 的Firebase数据库示例,并意识到它以下列方式存储其数据:
我不太熟悉NoSQL技术,并试图理解为什么我们必须坚持每个post实体两次 - 在posts和user_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);
}
// …Run Code Online (Sandbox Code Playgroud)