How to query one field then order by another one in Firebase cloud Firestore?

前端 未结 6 972
粉色の甜心
粉色の甜心 2021-02-13 04:14

I\'m struggling to make a (not so) complex query in firebase cloud firestore.

I simply need to get all docs where the id field ==

6条回答
  •  别跟我提以往
    2021-02-13 04:40

    My Workaround

    If you're googling this you've probably realized it can't be done traditionally. Depending on your problem though there may be some viable workarounds, I just finished creating this one.

    Scenario

    We have an app that has posts that appear in a feed (kind of like Reddit), each post has an algorithmic score 'score' and we needed a way to get the 'top posts' from 12-24 hours ago. Trying to query sorted by 'score' where timestamp uses > and < to build the 12-24 hour ago range fails since Firebase doesn't allow multiple conditional querying or single conditional querying with an descending sort on another field.

    Solution

    What we ended up doing is using a second field that was an array since you can compound queries for array-contains and descending. At the time a post was made we knew the current hour, suppose it was hour 10000 since the server epoch (i.e. floor(serverTime/60.0/60.0)). We would create an array called arrayOfHoursWhenPostIsTwelveToTwentyFourHoursOld and in that array we would populate the following values:

    int hourOffset = 12;
    while (hourOffset <= 24) {
        [arrayOfHoursWhenPostIsTwelveToTwentyFourHoursOld addObject:@(currentHour+hourOffset)];
        hourOffset++;
    }
    

    Then, when making the post we would store that array under the field hoursWhenPostIsTwelveToTwentyFourHoursOld

    THEN, if it had been, say, 13 hours since the post was made (the post was made at hour 10000) then the current hour would be 10013, so we could use the array-contains query to see if our array contained the value 10013 while also sorting by algorithm score at the same time

    Like so:

    FIRFirestore *firestore = [Server sharedFirestore];
    FIRCollectionReference *collection = [firestore collectionWithPath:@"Posts"];
    FIRQuery *query = [collection queryOrderedByField:@"postsAlgorithmScore" descending:YES];
    query = [query queryWhereField:@"hoursWhenPostIsTwelveToTwentyFourHoursOld" arrayContains:@(currentHour)];
    query = [query queryLimitedTo:numberToLoad];
    

    Almost Done

    The above code will not run properly at first since it is using a compound index query, so we had to create a compound index query in firebase, the easiest way to do this is just run the query then look at the error in the logs and firebase SDK will generate a link for you that you can navigate to and it will auto-generate the compound index for your database for you, otherwise you can navigate to firebase>database>index>compound>new and build it yourself using hoursWhenTwelveToTwentyFourHoursOld: Arrays, score: Descending

    Enjoy!

提交回复
热议问题