如何在本地存储具有复杂结构的 Google Cloud Firestore 数据?

How to store Google Cloud Firestore data locally having a complex structure?

我在 Google Cloud Firestore 上有一个数据库,我正在 Kotlin 中制作一个 Android 应用程序来访问它。数据库只有一个集合,但是文档很多。 一次用户只需要大约 5-6 个文件。在线数据库的原因是将来可以轻松添加更多文档。 下载后,下载的文档数据很少会更新。 所以,下载后,我想让他们在没有网络的情况下访问。

我的问题是,即使文档存储在本地,要访问它们我必须设置一个侦听器,因此代码变得异步,这使事情变得更加复杂。所以我想以不同的方式将它们存储在本地,以便我可以毫不延迟地访问数据 .

这是我从缓存中访问文档的方式:

val db = FirebaseFirestore.getInstance().collection("courses")
db.document("doc_name").get(Source.CACHE).addOnCompleteListener { task ->
    if (task.isSuccessful) {
        // what to write here
        // to store the data locally
        // if some other method is used ?     
    } else {
        // documents need to be re-downloaded
    }
}

我的问题是存储数据的最佳方式是什么以及如何实施该最佳方式?鉴于所有文档都具有相似但非常复杂的结构,如下所示。

collection/doc_example/:

|----string
|
|----string
|
|----map
|    |----string
|    |----int
|
|----int
|
|----array{size=3, type=int}
|
|----string
|
|----map
|    |----int
|    |----array{size=variable, type=map}
|         |----map
|              |----string
|              |----int
|              |----array{size=variable, type=string}
|
|----array{size=variable, type=string}
|
|----array{size=variable, type=string}    /* note - this array is optional */
|                                            
|----array{size=variable, type=map}
     |----map
          |----string
          |----string     
          |----int
          |----string
          |----string    /* note - this one string is optional */

My question is what is the best way to store my data and how to implement that best way?

如果您想在 phone 中保留数据,您可以尝试使用 SQLite or Room Persistence Library,您可以在其中根据您向我们展示的结构定义数据库,并能够查询存储的文档.

这样,首先获取文档后,您可以将其存储在数据库中。在以后尝试获取它时,您应该首先检查它是否存储在您的数据库中。如果不是,那么您可以继续从 Firestore 获取它(并保存在本地)。

我用来在本地存储和保存数据的另一个资源是 Android Shared Preferences。恕我直言,这比使用 SQLite 或 Room 更简单,但它对复杂数据结构有限制(AFAIK,它只能存储原始数据和 StringSets)...好消息是您可以 保存您的文档作为 JSON 字符串 并轻松将其存储在您的共享首选项中(实际上,您的文档结构对于 JSON 格式来说确实足够,因为它具有映射、数组等)。

如果使用此功能,则遵循相同的原则,并在必须从 Firestore 获取文档之前检查共享首选项中是否存在该文档。