Solution 1 :
I see two solutions:
-
Assuming the posts are evenly distributed over the 48h, use the timestamp as random index as mentioned in the answer you are linking
-
Code the timestamp in a way that you dont need to use a range to filter over the last 48h. For instance you could add a field
timechunk
that splits time in chunks of 5h and is incremented by 1 at every chunk and then just add to your query the last 10 chunkslet postsRef = db.collection("posts") queryRef = postsRef.whereField("random", isGreaterThanOrEqualTo: lowValue) .whereField("timechunk", in: ["chunk1", "chunk2", "chunk3", "chunk4", "chunk5", "chunk6", "chunk7", "chunk8", "chunk9", "chunk10"]) .order(by: "random") .limit(to: 1)
This way you get a random post over the last 50h-ish. I am using this solution for a similar problem.
Problem :
In my situation, I need to read random posts of the last 48hours. I have seen the method where we need to create a random id and query with isGreaterThanOrEqualTo
range to get random posts. But I also need to use it for the timestamp. As I know, Firestore doesn’t let range queries on different fields in one query. How can I get random posts of the last 48hours?
--- posts (collection)
| |
| --- postid (documents)
| |
| --- country_code: "TR"
| |
| --- timestamp: "Server.Timestamp"
| |
| --- post_text: "Some Text"
Comments
Comment posted by l1b3rty
Can you define clearly “random posts of the last 48hours”? What have you tried?
Comment posted by Nasir
App stores a post with auto-Id. Every post document has a timestamp, country_code fields. I am just trying to fetch random posts within a country but in 48hours and show them to the user. I will edit the question with my post’s data structure. Actually, I haven’t tried anything yet, because I clearly see that it is not possible with Firestore limitations.
Comment posted by l1b3rty
And what do you mean by “I have seen the method where we need to create a random id and query with isGreaterThanOrEqualTo range to get random posts”?
Comment posted by stackoverflow.com/a/46801925/5817560
I mean this method: