按日期构建 Firebase 数据库的正确方法



所以我的服务器上有几个对象正在监视,每小时我都想将这些对象的读数发布到我的数据库中。我需要一种简单的方法来拥有这些数据,以便我可以按数组中的日期对它们进行排序,轻松获取特定日期的值,并清理特定日期不再需要的旧数据。

我目前对如何构建数据有两种想法:

1(按日期部分将其分成块

objects
- objectA
- 2020
- 01
- 22
- 01
- property1 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- 02
- property1 : "Value at 2 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 2 o'clock on the 22nd of Jan, 2020"
...
- objectB
...

此方法为我提供了轻松查询特定日期或月份并从中获取值的优势。它还可以轻松地让我清除特定日期或月份的旧数据。

但是缺点是我想不出一种简单的方法来查询它,以将我应用程序中的数据作为按时间排序的平面列表(在大多数情况下,这就是我需要数据的方式(

2( 将数据存储为属性的日期平面列表

objects
- objectA
- 2020:01:22:01
- property1 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- 2020:01:22:02
- property1 : "Value at 2 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 2 o'clock on the 22nd of Jan, 2020"
...
- objectB
...

此模型可以更轻松地在应用程序中以我需要的格式获取对象,但是现在很难仅查询特定的日期或月份。清除特定日期或月份的旧数据并不容易。

在实践中这样做的好方法是什么? 我的方法要么好,还是我应该完全做其他事情? 如果一个好,我如何解决我的缺点?

我的应用程序是用 Kotlin 编写的,那么 kotlin 中是否有一种简单的方法可以从选项 1 查询数据库并让它在平面列表的 for 中返回?

这样:

objects
- objectA
- 2020:01:22:01
- property1 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- 2020:01:22:02
- property1 : "Value at 2 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 2 o'clock on the 22nd of Jan, 2020"
...
- objectB
...

比选项 1 更好,始终倾向于使用平面数据结构而不是嵌套结构。如果在检索月份或日期时遇到困难,可以将它们添加为属性:

objectA
2020:01:22:01
property1 : data
month : 01
day : 22

但您也可以使用getKey(),然后使用split检索月份和日期。

https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html?m=1

我认为最好的方法是使用时间戳进行存储,我总是使用时间和日期依赖关系发生的时间戳

objects
- objectA
- 1579721879
- property1 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- 1579721964
- property1 : "Value at 2 o'clock on the 22nd of Jan, 2020"
- property2 : "Value at 2 o'clock on the 22nd of Jan, 2020"

或者像这样

objects
- 1579721879 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- 1579721889 : "Value at 1 o'clock on the 22nd of Jan, 2020"
- 1579721899 : "Value at 2 o'clock on the 22nd of Jan, 2020"