Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the latest record from Firebase Realtime Database

I'm using Pyrebase to receive data from a realtime database. Actually I can receive data directly, but I need only the latest record.

This is the realtime database:

like image 737
vargaking Avatar asked Sep 02 '25 10:09

vargaking


1 Answers

Assuming the largest key (4 here) is the most recent record's, here is how to directly retrieve it with pyrebase:

firebase = pyrebase.initialize_app(config)
db = firebase.database()

last_record = db.child('input').order_by_key().limit_to_last(1).get().val()

print(last_record)
# should print OrderedDict([('4', {'input1': ..., 'input2': ..., 'input3': ...})])

order_by_key orders in ascending order by default, and limit_to_last(1) ensures you only retrieve one record, being the last one in the query.

However there is a bug for calling order_by in the pyrebase library. Fortunately a fork of it, pyrebase4, has it fixed so ensure to use this one:

$ pip uninstall pyrebase && pip install pyrebase4
like image 200
michaeldel Avatar answered Sep 04 '25 23:09

michaeldel