Firestore whereEqualTo, orderBy and limit(1) not working
Asked Answered
P

1

19

I want to query my Workout Collection for the latest workout from a routine. Meaning I query with whereEqualTo my routineKey, order it by the Started TimeStamp in descending order and then limit to 1 and then take the this 1st Key/Id of the Workout.

However this does not work. whereEqualTo and orderBy work separately but not combined. What am I doing wrong?

fm.getColRefWorkout().whereEqualTo("routineKey", routineKey).orderBy("startTimeStamp", Query.Direction.DESCENDING).limit(1).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { 
                @Override
                public void onSuccess(QuerySnapshot documentSnapshots) {
                    workoutKey = documentSnapshots.getDocuments().get(0).getId();
                    //To stuff with this workoutKey
                }
            });
Pancreatin answered 12/5, 2018 at 10:41 Comment(0)
K
44

This query will not work unless you create an index for it. This can be done, by creating it manually in your Firebase Console or if you are using Android Studio, you'll find in your logcat a message that sounds like this:

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

You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically.

Kossuth answered 14/5, 2018 at 6:55 Comment(7)
Thanks for the answer! Haven't got a LogCat message but I created an index manually it worked.Pancreatin
FirebaseFirestore.instance .collection('messages') .where('encSenderUId', isEqualTo: _loggedInUserId) .orderBy('sentOn', descending: false) .snapshots(), I want to do orderBy by SentOn field, not by encSenderUId then why firebase console says to encSenderUId to index by providing link. Its weird. Kindly suggest. Thanks.Trifle
@Trifle Without seeing the entire code, I can't be much of a help. So please post a new question using its own MCVE, so I and other Firebase developers can help you.Kossuth
I have created index for the same and it worked. It was odd but I did to solve this issue. Thanks.Trifle
I broke my head over this issue - documentation says where and orderBy can't be used on different fields, whereas the answers above suggest that compound index creation would suffice. I am trying to do this and it doesn't work collection('users').where('uid', isNotEqualTo: user.uid).orderBy('accountCreationDate', descending: false)Moro
@Moro Without seeing your index, it is hard to tell why it isn't working the way you expect. So please post a new question, here on StackOverflow, using its own MCVE, so I and other Firebase developers can help you.Kossuth
thanks, just posted my question here - #71939362Moro

© 2022 - 2024 — McMap. All rights reserved.