Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Firebase data using timestamps

Here is my current data design on Firebase (data is simply a list of jsons at the "events" reference). The fields timestamp, action, and duration are fixed, and there might be more optional fields added later.

backend-7f34e
    events
        -KQ30Lc6lasdfasdfAi1URf
            action: "Get ready"
            duration: 100
            timestamp: 1472167504389

        -KQ30MM8Fgasdf_o10TW
            action: "Run"
            duration: 1890
            timestamp: 1472167507411

I need to be able to retrieve data from a timestamp range [start, end]. Do I need to use timestamp as the key? What would be a better way to structure the data?

like image 977
Dzung Nguyen Avatar asked Mar 24 '26 19:03

Dzung Nguyen


1 Answers

Use OrderByChild combined with startAt and endAt

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventsReference = databaseReference.child("events");

Query query = eventsReference.orderByChild("timestamp").startAt(1472167504389);
query.addValueEventListener(new ValueEventListener).....
....

StartAt takes double as the argument, so structure your data accordingly.

More info - https://www.firebase.com/docs/web/api/query/startat.html

like image 176
Veeresh Charantimath Avatar answered Mar 28 '26 03:03

Veeresh Charantimath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!