Firestore查询数据顺序

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

Firestore Query Data Order

问题

我正在从Firestore中检索数据,并希望添加一个检索顺序,因此我尝试了以下代码:

Query query = firebaseFirestore.collection("docs").orderBy("date", Query.Direction.DESCENDING/*ASCENDING*/);
FirestoreRecyclerOptions<download> docsFirestoreRecyclerOptions = new FirestoreRecyclerOptions.Builder<download>()
        .setQuery(query, download.class)
        .build();

在"date"字段中,我以字符串类型添加了时间和日期,例如:

> 02:42:31 - 2020/08/01

通过这种方式,我希望确保最新的帖子出现在循环视图的顶部。它在当天运行得很好,但是第二天,如果时间是:

> 01:00:00 - 2020/08/02

它会出现在之前一天添加的帖子之前。是否有更好的方法来从Firestore中排序数据?

英文:

I am retrieving data from Firestore and I want to add an order of retrieving it, so I have tried this code:

 Query query = firebaseFirestore.collection(&quot;docs&quot;).orderBy(&quot;date&quot;, Query.Direction.DESCENDING/*ASCENDING*/);
    FirestoreRecyclerOptions&lt;download&gt; docsFirestoreRecyclerOptions = new FirestoreRecyclerOptions.Builder&lt;download&gt;()
            .setQuery(query, download.class)
            .build();

In date, I am adding time and date in String type like

> 02:42:31 - 2020/08/01

by this, I want to make sure the newest post appears on the top of recycler view.
it works well in this day but the next day if the time let's say

> 01:00:00 - 2020/08/02

It is will appear before the post that added the previous day. Is there a better way to ordering data from Firestore?

答案1

得分: 2

当然可以。与其将时间和日期存储为字符串,你可以将其存储为Java Date(Date是Firestore支持的数据类型之一),或者存储为Firestore Timestamp对象。下面是一个回答,可以帮助你实现这一点:

> https://stackoverflow.com/questions/48474957/servertimestamp-is-always-null-on-firebase-firestore/48475027#48475027

现在,将date属性的类型设置为Firestore Timestamp,你的查询将正常工作。

但是,如果你坚持将日期和时间存储为字符串,那么你的选择是将它们存储为既能按字典顺序排序又能按时间顺序排序的格式。

ISO 8601格式如下所示:

20200802T131425

这是我回答这个问题时的当前时间。

2020年8月2日 下午1:14:25 UTC
英文:

> Is there a better way to ordering data from Firestore?

Sure it is. Instead of storing the time and date as a String, you can store it either as a Java Date, the Date being a Firestore supported data type or as a Firestore Timestamp object. Here is an answer that can help you achieve that:

> https://stackoverflow.com/questions/48474957/servertimestamp-is-always-null-on-firebase-firestore/48475027#48475027

Now, having the type of the date property as Firestore Timestamp, your query will work perfectly fine.

However, if you insist to store the dates and times as Strings, the option that you have is to store them in a format that can be sorted lexicographical and chronological at the same time.

The ISO 8601 format looks like this:

20200802T131425

That's the current time I'm answering this question.

August 02, 2020 1:14:25 PM UTC

huangapple
  • 本文由 发表于 2020年8月2日 15:56:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63213688.html
匿名

发表评论

匿名网友

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

确定