2

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" 
Nasir
  • 57
  • 5
  • Can you define clearly "random posts of the last 48hours"? What have you tried? – l1b3rty Jul 13 '20 at 16:18
  • 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. – Nasir Jul 13 '20 at 16:26
  • 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"? – l1b3rty Jul 13 '20 at 17:57
  • I mean this method: https://stackoverflow.com/a/46801925/5817560 – Nasir Jul 13 '20 at 18:06

1 Answers1

1

I see two solutions:

  1. Assuming the posts are evenly distributed over the 48h, use the timestamp as random index as mentioned in the answer you are linking

  2. 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 chunks

    let 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.

l1b3rty
  • 3,333
  • 14
  • 32