Skip to content Skip to sidebar Skip to footer

Query On Date Field In Firestore Not Working

I'm new to programming and only as a hobby, usually if I have a problem I can find the answer on the internet somewhere, but having spent best part of 2 days and still can't figure

Solution 1:

I get an empty array despite knowing there are results that should be returned. If I comment out the whereGreaterThan() line I get all results returned.

You are getting an empty array most likely because of the following line of code:

db.collection("snookerResults")
    .whereGreaterThan("date", startDate)
    .whereEqualTo("homeTeam", team)
    .get()
    .addOnSuccessListener {...}

And this is because calling .whereGreaterThan() along with .whereEqualTo() in the same query, require an index. This index can be created manually in your Firebase Console or if you are using Android Studio, you'll find in the logcat a message that sounds like this:

FAILED_PRECONDITION: The query requires an index. You can create it here: ...

You can simply click on the link or copy and paste the URL into a web browser and your index will be created automatically. Wait a few minutes until the index is created and you'll get the desired results.

However, this approach might not be the best one, since you need to create an index for each homeTeam in your database. It will work if you have a few or a fixed number of teams but it will be hard if you have lots of them, case in which it's recommended to duplicate the data. This practice is called denormalization and it's quite common practice when it comes to Cloud Firestore. If you are new to the NoSQL database, for a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database. It's for Firebase Realtime Database but the same principles apply to Cloud Firestore. Besides that, I think you might also be interested in my answer from the following post:

What is denormalization in Firebase Cloud Firestore?

So in your particular case, I'd create a new collection that looks like this:

Firestore-root
  |
  --- homeSnookerResults (collection)
         |
         --- homeTeamId (document)
               |
               --- allResults (collection)
                     |
                     --- resultIdOne (document)
                           |
                           --- //result object properties

In this case, a query that looks like this, will do the trick:

db.collection("homeSnookerResults")
    .document(homeTeamId)
    .collection("allResults")
    .whereGreaterThan("date", startDate)
    .get()
    .addOnSuccessListener {...}

Case in which, no index is required.

Post a Comment for "Query On Date Field In Firestore Not Working"