Swift - How to Create Sort Query as Descending on Firebase

Swift - How to create Sort query as Descending on Firebase?

self.posts = self.posts.reverse()

To save NSDate instances, I personally use timeIntervalSinceReferenceDate() which returns an NSTimeInterval (which is a Double), which you can then save in Firebase. When reading the data, you can obtain the original NSDate with init(timeIntervalSinceReferenceDate:).

Firebase query sort order in swift?

When Firebase loads the data into your tableView data source array, call this:

yourDataArray.sortInPlace({$0.date > $1.date})

Swift 3 Version:

yourDataArray.sort({$0.date > $1.date})

Swift 4 Version:

yourDataArray.sort(by: {$0.date > $1.date})

How to get data from firebase in descending order of value?

Firebase does not offer any way to reverse the sort order via a query. However, if you store your scores as negative values, then it's super easy.

Here's a structure

scores
score_0
amt: -20
score_1
amt: -10
score_2
amt: -12
score_3
amt: -1
score_4
amt: -22

and then the code that reads the top three 'high' scores of 22, followed by 20 and 12

    let scoresRef = self.ref.child("scores")
let queryRef = scoresRef.queryOrdered(byChild: "amt").queryLimited(toFirst: 3)

queryRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
print(snap.value)
}
})

and the output

Optional({
amt = "-22";
})
Optional({
amt = "-20";
})
Optional({
amt = "-12";
})

and of course, if there's a limited number of scores, they could be read into an array and sorted as well.

For completeness and if you don't want to store scores as negative values, here's how that would work.

    let scoresRef = self.ref.child("scores")
let queryRef = scoresRef.queryOrdered(byChild: "amt").queryLimited(toLast: 3)

queryRef.observeSingleEvent(of: .value, with: { snapshot in

var scoresArray = [Int]()

for child in snapshot.children {
let snap = child as! DataSnapshot
let score = snap.childSnapshot(forPath: "amt")
scoresArray.append(score.value as! Int)
}

scoresArray = scoresArray.reversed()
print(scoresArray)
})

The above code reads in the three highest values via queryLimited(toLast) which are 12, 20 and 22 and populates an array. The array can be reversed which sorts descending 22, 20 and 12.

A final option is to read them in as 12, 22, 20 but insert each amt into the array at position 0. So 12 would be at index 0, then 22 would be at index 0 and 12 would be at index 1 etc.

Firebase query ordering by child not working

Firebase Realtime Database results are always in ascending order. There is no way to get them in descending order from the database, so you will have to reverse the results in your application code.

A simple option for this is to insert each item at the top of the table, instead of appending it to the bottom as you do now:

self.table.insert(video, at: 0)

The alternative would be to store inverted values in your database, like: userTime: -1654342137807. That way the ascending order that the database uses, will actually be what you want.

Also see:

  • How to get data from firebase in descending order of value?
  • Swift - How to create Sort query as Descending on Firebase?
  • Firebase query sort order in swift?

Swift 4: Sorting data with Firestore

The default order of Firestore is ascending. So you get the 3 meals with the least view_count. Try to take the order method with descending option:

func order(by field: String, descending: Bool) -> Query

How to Cloud Firestore Data Sort by Desc SwiftUI

The code is trying to use query which needs so called Composite Index. Actually according to the documentation it should be possible by the link that is in the error massage:

If you attempt a compound query with a range clause that doesn't map
to an existing index, you receive an error. The error message includes
a direct link to create the missing index in the Firebase console.

Just open it in browser and create the index. That's all! :)

Sorting in descending order in Firebase database

Unfortunately firebase doesn't allow returning by descending order. I have generally just reversed the order of the results returned client side.

If your data query is too large to sort client side you can do

firebase.database().ref('books').orderByChild('ups').limitToLast(2)

and then invert the results from there. Documentation can be seen here

How to sort data with a limit filter Firestore

I suggest giving each document a timestamp field. I would modify your query to look something more like this.

db.collection("References").whereField("followers", arrayContains: uid).order(by: "timestamp", descending: true).limit(to: 10)

//put the timeStamp in a global variable
var lastTimestamp: Timestamp?
lastTimeStamp = snapshot.documents?.data()["timestamp"] as! Timestamp

Then, when you make your next request, your query should look something like this

db.collection("References").whereField("followers", arrayContains: uid).whereField("timestamp", isLessThan: lastTimestamp).order(by: "timestamp", descending: true).limit(to: 10)

//then repeat by putting the last documents timestamp into the global variable
lastTimeStamp = snapshot.documents?.data()["timestamp"] as! Timestamp


Related Topics



Leave a reply



Submit