java - 如何构建博客 API 多对多关系的 Firestore JSON

标签 java android firebase google-cloud-firestore

Firebase/FireStore 新手,没有 NoSQL 经验。

在学习 Android 以及通过为自己构建应用程序来学习 Room 时,我意识到我需要一个实时数据库解决方案。但我一直坚持构建模型结构。

这是 JSON 格式:

{
 "published": "date",
 "title": "This is the title",
 "content": "This is the body",
 "tags": [
  "tag1", "tag2"
 ]
}

问题出在 tags 多对多关系上。意识到 FireStore 可以通过索引解决这个问题,但如何使用集合和文档构建数据?谁能详细解释一下吗?

最佳答案

假设您问题中的代码 fragment 是一个 post 对象,我建议您使用如下所示的数据库架构:

Firestore-root
    |
    --- posts (collection)
          |
          --- postId (document)
                |
                --- published: "date"
                |
                --- title: "This is the title"
                |
                --- content: "This is the body"
                |
                --- tags
                     |
                     --- tag1: true
                     |
                     --- tag2: true

根据官方文档关于modelling data在 Cloud Firestore 数据库中:

Each document contains a set of key-value pairs. Cloud Firestore is optimized for storing large collections of small documents.

因此,这是我能为您的应用程序想到的最佳数据库结构,正如您所看到的,tags 属性不是 array 而是 map 。对于此类对象,这是最佳实践。请参阅有关 working with arrays, lists, and sets 的官方文档.

2018 年 8 月 13 日编辑:

根据有关 array membership 的更新文档,现在可以使用 whereArrayContains() 方法根据数组值过滤数据。一个简单的例子是:

CollectionReference citiesRef = db.collection("cities");
citiesRef.whereArrayContains("regions", "west_coast");

This query returns every city document where the regions field is an array that contains west_coast. If the array has multiple instances of the value you query on, the document is included in the results only once.

关于java - 如何构建博客 API 多对多关系的 Firestore JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51672302/

相关文章:

java - 可滚动的 JDesktopPane?

android - 如何在ffmpeg中合并音频和两个视频文件?

android - Hilt - 如何注入(inject) ViewModel 接口(interface)?

android - 显示图像字符串资源(xml)android

firebase - 从服务帐户跨项目访问 Firebase 数据库

java - 滑动手势非常慢,...如何加快 Android 中的滑动手势?

java - 父类(super class)上的 PostConstruct 注释

java - 如何在没有 EventListener 的情况下从 Firebase 检索数据?

java - 如何配置依赖于ejb jar的war并结合创建ear文件

ios - 为什么我不能以这种方式将数据添加到 Firebase 中?