Firestore get random documents of last 48 hours

Viewed 147

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" 
1 Answers

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.

Related