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/