How to Get Data from Firebase in Descending Order of Value

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.

How to arrange data in descending order in Firebase - Python

Use the following query to retrieve the top 20 people in point list.

data_ref = db.reference('data')
snapshot = data_ref.order_by_child('Points').limit_to_first(20).get()
for key in snapshot:
print(key)

Made query with the help of docs

flutter - get slices of data from firebase realtime database, sorted by descending likes for pagination

The Firebase Realtime Database always returns results in ascending order. If you want to display them in descending order, you'll need to reverse the results in your application code.


If you want the second-to-last page of results, you need to use endAt instead of startAt:

_database.orderByChild('numFav').endAt(endAtValue, key: endAtKey).limitToLast(num)

If your endAtValue is not guaranteed to be unique (as the name numFav suggests), you'll want to also keep the key of the node that you want to anchor on to disambiguate between nodes with the same numFav value.


Firebase added startAfter/endBefore methods to the Realtime Database API last year, so you might want to consider using those to exclude the first/last item of the next/previous page from the results.


A query on a named property like numFav requires that you define an index in your rules before it can be executed on the server. Once you define the index in your rules, the query will be executed on the server.

How to arrange firebase database data in ascending or descending order?

If you want to order the results of a Firebase database query, you need to use numbers as values and not Strings. If you keep the Strings, as I see in your screenshot, you need to know that the Strings are ordered lexicographically and I'm sure this is not what you are looking for.

The simplest way to order data in ascending or descending order, would be on client side. Firebase can order the results in ascending order by a given property by default. There is no method in Firebase to order in descending order but there a few tweaks that can be made.

If you are using a RecyclerView to display data, the simplest way would be to use the following code:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);

This approch will reverse you the order.

Another approach would be to create your own adapter that extends FirebaseListAdapter and override getItem() method.

Another approach would be to get the data from the database, add it to a Collection, a List would be a good solution and then use Collections.reverse(yourList);.

Sort items in descending order by the number of childs count Firebase Realtime Database

That's not possible directly in the Firebase query. You would have to fetch the data once which will be in ascending order, then reverse that and process it using Javascript yourself.

const db = firebase.database()
db.ref("posts").once("value").then((snapshot) => {
const rawData = []
snapshot.forEach((post) => {
const postName = post.name
const upvotes = Object.keys(post.upvotes).length
const downvotes = Object.keys(post.downvotes).length
rawData.push({name: postName, upvotes: upvotes, downvotes: downvotes, score: upvotes - downvotes })
})
console.log(rawData)
})

Now the only part left is you would have to sort this array based on the property score.

I have a few suggestions:

  1. This data structure is not ideal or economical. Firestore would have been a better choice both for structure and querying but this existing structure can be improved a bit.
  2. There is no property called ".size" as mentioned in your screenshot. You must store a count of upvotes and downvotes explicitly in their respective nodes. Then you would be able to use .orderByChild("upvotes.size") in the query.

Let me know if you need more clarification.

Sort Firebase data in ascending/Descending Order

You can get sorred data in ascending order from firebase using orderByChild function.you will need to create indexes on table .
Refer firebase sorting data section
https://firebase.google.com/docs/database/android/lists-of-data

// Descending order:

Do this task at client side as you already have sorted list. Use collections inbuilt function to reverse the list Collections.reverse(inputList)

Hope this helps you :)



Related Topics



Leave a reply



Submit