首页 > 解决方案 > 如何构建博客 API 多对多关系的 Firestore JSON

问题描述

Firebase/FireStore 新手,没有NoSQL.

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

这是 JSON 格式:

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

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

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


假设您问题中的片段是一个post对象,我建议您使用如下所示的数据库模式:

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

根据有关Cloud Firestore 数据库中建模数据的官方文档:

每个文档都包含一组键值对。Cloud Firestore 针对存储大量小文档进行了优化。

所以这是我能为您的应用程序想到的最佳数据库结构,正如您所看到的,该tags属性不是 an arrayis a map。这是此类对象的最佳实践。另请参阅有关使用数组、列表和集合的官方文档。

2018 年 8 月 13 日编辑:

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

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

此查询返回区域字段是包含 west_coast 的数组的每个城市文档。如果数组具有您查询的值的多个实例,则该文档仅包含在结果中一次。


推荐阅读