如何按严格的顺序从 NoSQL 数据库中获取数据?

huangapple go评论85阅读模式
英文:

How do I fetch data from nosql database in strict order?

问题

我正在使用Firestore数据库。我需要按特定顺序从Firestore中获取数据。

我的方法是:

我有一个名为section的集合中的文档集合,其中包含一个整数字段order,用于指定其在页面上的位置。因此,它们基本上有一个顺序,可以使用OrderBy("order")按特定顺序获取数据。当创建一个section时,order也可以从前端传递给它。

但是这种方法有一个缺点:当有人使用已经存在于Firestore数据库中的order创建一个section时,我必须基本上按给定的order创建该section,并将所有在创建的section之后的section的order字段递增1。这样效率很低。

其次,我可以创建一个表示order的整数数组,并在每次创建section时更改该数组中的order。这样我就不必访问Firestore数据库,可以直接在数组中进行更改。是否有特定的方法可以按照某个数组中定义的顺序获取数据?

我尝试了使用in关键字,类似于db.collection("section").Where("order", "in", []int{1,2,3}),但结果并不严格按照1, 2, 3的顺序返回。

英文:

I am using the Firestore database. I have to fetch the data from Firestore in a specific order.

My Approach:

I have a collection of documents in a collection named section with an integer field order that specifies where it lies on the page. So they basically have an order which is used to fetch data in a specific order by using OrderBy("order"). The order is also a parameter that can be given from the front-end side when creating a section.

But this has a drawback: When someone creates a section with the order that exists in the Firestore database, I have to basically create that section with the given order and increment the order field of all the section that comes after the created section by one. This is inefficient.

Secondly, I can create an array of integers that represent order and change the order in that array every time a section is created. So I don't have to hit the Firestore database and can make changes in the array itself. Is there any specific method to fetch data in the order as defined in some array?

I tried in keyword like db.collection("section").Where("order", "in", []int{1,2,3}) but the result is not strictly in the order 1, 2, 3

答案1

得分: 1

我能想到的最好的解决方案是在你的文档中添加一个时间戳值。这样,你可以创建一个查询并按升序排序结果。第一个文档将是最早添加的文档。如果你需要在两个其他文档之间添加一个文档,那么你需要读取前一个文档和后一个文档的时间戳,然后设置中间的时间戳。Firestore时间戳的精度是纳秒级别的,这意味着碰撞的风险并不太高。然而,如果你有两个具有相同时间戳的文档,那么你可以添加第二个orderBy调用。

英文:

The best solution I can think of would be to add a timestamp value inside your documents. In this case, you can create a query and order the results ascending. The first document will be the oldest added document. If you need to add a document in between two other documents, then you have to read the timestamp of the document before and the document after, and then set the timestamp in between. The precision of the Firestore timestamp is nanoseconds, this means that the risk of collision is not so high. However, in case you have two documents with the same timestamp, then you can add a second orderBy call.

huangapple
  • 本文由 发表于 2023年5月19日 17:41:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76287854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定