Random data from Firebase Realtime Database

Deepak Goyal
3 min readDec 27, 2019

I’m using Firebase in one of my apps. I want to display the random data in my app from the Realtime Database. Realtime Database is a NoSQL database and there is no direct query to get the random record. So in this article, you will get to know how to have this functionality in your app/project.

Task:

Display a random thought from the list of saved thoughts in the Realtime Database.

Database Structure:

database_structure

As you can see I have added 5 thoughts for now.

author: who is the author of the thought.

createdAt: Timestamp in milliseconds since epoch. When the thought was saved in the database. This will be used to get random thoughts. We will generate a random timestamp and then we will fetch the thought near to that timestamp.

tag: tag of thought like love, life, inspirational, etc.

thought: Thought Sentence.

views: No of times this thought has been viewed.

Database Rules:

As we will use the createdAt field to get the random thought so we need to add an index on that field. Below you can find the screenshot of database rule.

Logic:

Now it is time to create a logic to get the random thought.

Get Random Timestamp.

The minimum value of the timestamp in the database is 1577441685097 so we will generate the random timestamp after this value. Consider the max value is the current time. We will use the below function.

// min timetamp in the database
var min = 1577441685097;
// max timestamp
var max = new Date().getTime();
// generate random timestamp.
function getRndTimestamp(min, max) {
return Math.floor(Math.random() * (max — min) ) + min;
}

Use the below code to get the random thought

var randomTime = getRndTimestamp(min, max);
var limit = 1;
// get 1 thought equal or after this timestamp
var snap = await firebase.ref(‘thoughts’)
.orderByChild(‘createdAt’)
.startAt(randomTime)
.limitToFirst(limit)
.once(‘value’);
if(snap.exists()){
// we have the data
parseSnapshot(snap);
}else{
// there are no thougths equal ro after the random time
// so get the thoughts before that timestamp.
snap = await firebase.ref(‘thoughts’)
.orderByChild(‘createdAt’)
.endAt(randomTime)
.limitToLast(limit)
.once(‘value’);
if(snap.exists()){
// we have the data
parseSnapshot(snap);
}else{
// probably there are no thoughts in the database.
console.log(‘No Random thought found’);
}
}

Working Video:

At the time of this video, I just have 7 records in the database. So the Probability of repeating the records is very high. But luckily the records are different.

Below is the complete source code link https://github.com/deepak786/Random-Thought-Firebase

Try the above solution and let me know your thoughts and any further improvements.

Thank You and don’t hesitate to buy me a coffee.

--

--

Deepak Goyal

I’m a Software Engineer. I love programming. #java #android #kotlin #dart #flutter #firebase