Sorting in Descending order Firebase results
I am sorry to tell you that unfortunately, Firebase doesn’t allow returning results by descending order by default. Here’s come my easy and fast solution!
Note: If you use Firestore Database and API you can click here to get the solution. Instead, if you are using Realtime Database and Firebase Admin API go ahead with the article.
The Database
First, let’s have a look at the data schema.
This is a toy schema, just to show you the solution to the problem.
The data are about films with just a few features: Genre, Title and Year.
My goal is to get films in descending order by Year. Let’s discover how to do it in successive sections.
Index your data on Firebase first!
I guess you have already looked on Google for a solution. Furthermore, I’m pretty sure you have visited different pages like the documentation page, and maybe StackOverflow that suggest you to use the function order_by_child(<value>) where value is the ordering criterion.
If you try to use that method as it is you will get an error.
import firebase_admin from firebase_admin import credentials from firebase_admin import db cred = credentials.Certificate("certificate.json") firebase_admin.initialize_app(cred, {'databaseURL': 'my.db.url'}) ref = db.reference('/Films') print(ref.order_by_child('Year').get())
Luckly, the error suggest us the solution: Create an Index On the attribute Year of our data.
Ok! Move on to solve this error.
How to add Index on Firebase
Despite this operation is quite simple, it is very delicate and requests precision and accuracy.
Hence, go on your Firebase’s realtime database console and select the rules tab.
Now, you have to add the right path of the collection you want to add the index, in my case the path is /Films. Then, set the .indexOn the attributes you desire, in my case Year.
Get data from Firebase in Descending Order
Finally, we are near to the end. As you probably know to get data from Firebase you have to use the .get() method on the reference object.
ref = db.reference('/Films') print(ref.get())
In general, you will get the result as they are inserted. Instead, once you add the index on data, you can call the previous mentioned method.
ref = db.reference('/Films') print(ref.order_by_child('Year').get())
As a result, you will get an OrderedDict object, but the elements are ordered by default in ascending order. Sadly, the method order_by_child(<value>) does not have a parameter to specify the ordering (ascending or descending) so we have to proceed manually.
# Get the data result = ref.order_by_child('Year').get() # Convert OrderedDict in a list films = list(result.items()) # Reverse the list films.reverse()
As you can see, the solution is very trivial and simple. We have just to convert the OrderedDict in a list and reverse it! Very easy!
Here is the complete code.
import firebase_admin from firebase_admin import credentials from firebase_admin import db cred = credentials.Certificate("certificate.json") firebase_admin.initialize_app(cred, {'databaseURL': 'my.db.url'}) ref = db.reference('/Films') print('No ordered request') for key, value in ref.get().items(): print(key, value) print('Ascending Order') for key, value in ref.order_by_child('Year').get().items(): print(key, value) print('Descending Order') # Get the data result = ref.order_by_child('Year').get() # Convert OrderedDict in a list films = list(result.items()) # Reverse the list films.reverse() for key, value in films: print(key, value)