Ehtesham Hasan
Ehtesham Hasan

Reputation: 4153

Firebase data sorting by timestamp

I have a Firebase node structure like the following.

categories
    category1
        timestamps
            23c491sdfwrasddgasd: true
            asdf8234dfjalskdask: true
            39fsdizxcasfgbskdf7: true
            2asqwizxov340bs9fms: true
    category2
        timestamps
            p23491sdfwrasddgasd: true
            asdfpovaskdrfskdask: true
    category3
        timestamps
            vmk339ffk3rasddgasd: true
            asdf8234dfjalskdvml: true
            bnwdwizxcasfgbskdf7: true

The timestamp keys are the keys generated by push(). I need to sort the categories by the oldest timestamp key they have. Only the oldest timestamp from the timestamps node will count.

Basically I need to sort the categories by the time they were modified for the first time.

Any help is welcome including tips to redesign the node.

Upvotes: 1

Views: 1711

Answers (1)

Hhorn
Hhorn

Reputation: 223

have you thought about flatting your Database? Change your Database Design to:

categories

  category1
    oldest_timestamp: 2asqwizxov340bs9fms
    timestamps
        23c491sdfwrasddgasd: true
        asdf8234dfjalskdask: true
        39fsdizxcasfgbskdf7: true
        2asqwizxov340bs9fms: true
  category2
    oldest_timestamp: asdfpovaskdrfskdask
    timestamps
        p23491sdfwrasddgasd: true
        asdfpovaskdrfskdask: true
  category3
    oldest_timestamp: bnwdwizxcasfgbskdf7
    timestamps
        vmk339ffk3rasddgasd: true
        asdf8234dfjalskdvml: true
        bnwdwizxcasfgbskdf7: true

Basically you have added a node called "oldest_timestamp". Now you can easily order your categories with a query.

Query myquery =  FirebaseDatabase.getInstance().getReference().child("categories").orderByChild("oldest_timestamp");

Don't forget to index that in your Firebase Database Rules for better Performance.

Upvotes: 1

Related Questions