Query Random Nodes from Firebase RealTime Database

Dhia Kennouche
Aug 22, 2017 · 1 min read

While building my app ( Revivan -A Travel Machine via Quotes ), I needed to query random nodes from the Firebase Database whenever the user refresh the layout, but Firebase doesn’t provide such a function for queries yet .

In order to achieve that, I had first to edit my Database nodes by adding a random index to each item.

FirebaseDatabase.getInstance().getReference().child("#your_node_path").runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
long max = mutableData.getChildrenCount();
for (MutableData data : mutableData.getChildren()) {
Node node = data.getValue(Node.class);
if (node!= null ) {
node.index = (int)(Math.random() * max +1);
data.setValue(node);
}
}
return Transaction.success(mutableData);
}

@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

}
});

PS: Don’t forget to add the index member to your Data Class also .

After finishing this step, using the Firebase provided functions for a query it will be so simple to Query random item/s . All what you need is generate a random number and use orderByKey() and limitToLast() and limitToFirst() provided functions.

int startIndex = (int)(Math.random() * MAX +1);
query = FirebaseDatabase.getInstance().getReference()
.child("#your_nodes_path")
.orderByChild("index")
.startAt(startIndex)
.endAt(startIndex + 4); //querying 4 random items

And here you have your query of random nodes :D .

Any questions or recommendation for better implementation please feel welcome to leave a comment ;) .

)

Dhia Kennouche

Full Stack Developer| Loading…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade