How do I structure the Firestore JSON of a blog AP

2019-06-10 05:04发布

New to Firebase/FireStore and have no experience in NoSQL.

While learning Android and as well as room by building an app for myself I realized that I need a real-time database solution. But I'm stuck at building the model structure.

This is the JSON format:

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

The problem is with the tags many-to-many relation. Realized that FireStore can solve this with indexation but how do I structure the data with Collections and Documents? Can anyone explain in details?

2条回答
Anthone
2楼-- · 2019-06-10 05:29

Assuming that the snippet in your question is a post object, I recommend you a database schema that looks like this:

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

Accordind to the official documentation regarding modelling data in a Cloud Firestore database:

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

So this is the best database structure I can think of for your app and as you can see, the tags property is not an array is a map. This the best practice when it comes to this kind of objects. Please aslo see the offical documentation regarding working with arrays, lists, and sets.

Edit 13 Aug 2018:

According to the updated documentation regarding array membership, now it is possible to filter data based on array values using whereArrayContains() method. A simple example would be:

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.

查看更多
劫难
3楼-- · 2019-06-10 05:43

I guess you should use this

Post:

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

Tags

[
{
    "tag_id":"xxx",
        "tag_name":"abc"
},
{
    "tag_id":"yyy",
        "tag_name":"abc"
}
]
查看更多
登录 后发表回答