How to mantain just a few elements in Firebase? - firebase

I'm doing an app with a Firebase Realtime Database connection, the issue is that I'll use Arduino to send measured information to firebase and visualize this in the app and I don't want to maintain all the information in the DB, just for example the last 10 sensed values. The DB is structured this way,
Root
"Humidity"
Datetime1 (Hour/minute/second Day-Month-year): Sensed Value 1
Datetime2 (Hour/minute/second Day-Month-year): Sensed Value 2
... Etc.
How can achive that? i dont want to do it in the app, i would like to do it in firebase itself (cause the users of the app are not going to be all the time in the app, and arduino is gonna still sending info)
I hope that you can help me, thanks in advance!

Instead of creating your schema like
+ Humedad
+ time_stamp_1: value
+ time_stamp_2: value
Do it something like,
+ Humedad
+ static_id_1
+ timestamp: value
+ reading: value
+ static_id_2
+ timestamp: value
+ reading: value
While updating / inserting these readings you loop for ten times on
to rewrite,
["static_id_1", "static_id_2", "static_id_3", ..."static_id_10"]
these values and reset the loop in your arduino again to rewrite on same keys.
Please do mention which library you are using to communicate with firebase for detailed explanation.

I don't want to do it in the app.
If you always need to have only 10 children available under a certain node, there is no need to do that in your application code. The simplest solution would be to write a function in Cloud Functions for Firebase, and each time the 11th element is written under that node, delete the oldest one. In this way, you'll only have 10 children.
If you intend in the future to create some statistics, then you should consider leaving the data as it is, and only retrieve the latest 10. Here's the official documentation regarding filtering data. So Query#limitToLast(int limit) will do the trick.

Related

How to get highest 10 scores with RestClient Unity from Firebase Realtime Database

I want to retrieve highest 10 scores from firebase . When i search stackoverflow i found some answers on here Firebase retrieve highest 100 score but i can not imagine how to implement them with REST API . My code is like this. I send request to end point and get response .
RestClient.Get<User>(databaseURL + getScoreText.text + ".json").Then(response =>
{
user = response;
UpdateScore();
});
Also for 2nd way, i can get all users' info by some json parser package and parse them and get the highest scores . But if my database gets bigger , i think i ll have problems . I need a way like "orderby". Do you know any way to implement "orderby" method to my restclient code ?
Reading the firebase docs:
Filtered data is returned unordered: When using the REST API, the filtered results are returned in an undefined order since JSON interpreters don't enforce any ordering. If the order of your data is important you should sort the results in your application after they are returned from Firebase.
It seems like scaling is a real limitation of the realtime database.
Firestore can do this pretty easily if you want to switch.
If you're sticking with realtime DB, I would save a separate database-reference that only ever contains the top 10 scores.
So when a player gets a new score, they would only upload it to this reference if it's higher than the 10th top score. This would mean you would only have a DB reference containing 10 or less top scores, and scaling wouldn't be a problem. I'm not very familiar with realtime DB, but I'm sure you could write a security to rule to enforce this in a secure, server authoritative manner, at the very least a cloud function.

How to expire a data after some specific time in firebase?

I am creating a School exam application where I give some questions to the database(firestore) and I want to expire those data from the database after some specific time!! how to do this in firebase
Client-side centric:
Record a "timestamp" upon creation of the exam.
Make the client show the exam as "expired" if and when ("now" >= "timestamp + # of days or hours")
OR:
Server-side...
If you actually want to delete the data from the db or mark it as "expired", you can create a Firebase function.
Let's assume that when creating an exam/question, you're adding an "expiration_time" when that data is supposed to be marked as "expired" or be deleted altogether.
Have your Firebase function do the following:
Query data where the "expiration_time" is less than or equal to "now".
For each result, mark that data as "expired" or delete it altogether, depending on your use case.
After you test your function and you know it works, make it so that it's a "Scheduled Firebase function" (google it if you don't know, it's easy to set up) - for example, make it run every minute.

Add multiple items from a firebase tree and display on firebase

Below is a picture of the firebase database tree . I have items a, b , c. I want the value of totalresult = a + b + c
My requirement is : As the value of a or b or c gets updated , it should get automatically reflected in the totalresult item value.
Is there a way to set in firebase to do it automatically instead running a piece of code everytime to add these and update in firebase
Am able to run a piece of code to add these and update the value in totalresult. But I have to run it manually every time, which is not an ideal solution
There isn't an internal way to do this in firebase realtime database.
That said, while you still have to write code, you can write a firebase function to trigger on updates to those fields, and then apply the update to total result. This will be automatic instead of manual, as the trigger will happen for every event on the database.
Documentation is here for how to create such a trigger (probably using the "onWrite" event).
Of course, there are a few things to be aware of:
There will be a period of time while the function is running that the data is not updated. In other words, you should be tolerant of inconsistencies. (You will likely also want to do the actual writing to the total using a transaction)
You need to be careful to not run the function (or exit early) when "tot/total result" is being updated, or you could get into an infinite loop of functions (it'd be best to have the result object elsewhere in your tree)

Firebase Database Unity differentiating between old and new data

I am building a chat engine using firebase in unity. I want to differentiate between the existing data and all the new data that gets added into the database. There is method once in web sdk of firebase which helps in differentiating between old and new data, is anyone aware if we have something similar on unity
There is no direct way to do this, one way that is a workaround is to add a timestamp value in all the entries maintained in the database and each time one subscribes for the new data we make use of the OrderByValue|OrderByKey and StartAt to do the same.
In the beginning value for StartAt will be 0 but post that whenever a child gets added we can update the StartAt value to that so that the next time client subscribes for the childAdded, it will only receive data post the last child.

Firebase - Structuring Data For Efficient Indexing

I've read almost everywhere about structuring one's Firebase Database for efficient querying, but I am still a little confused between two alternatives that I have.
For example, let's say I want to get all of a user's "maxBenchPressSessions" from the past 7 days or so.
I'm stuck between picking between these two structures:
In the first array, I use the user's id as an attribute to index on whether true or false. In the second, I use userId as the attribute NAME whose value would be the user's id.
Is one faster than the other, or would they be indexed a relatively same manner? I kind of new to database design, so I want to make sure that I'm following correct practices.
PROGRESS
I have come up with a solution that will both flatten my database AND allow me to add a ListenerForSingleValueEvent using orderBy ONLY once, but only when I want to check if a user has a session saved for a specific day.
I can have each maxBenchPressSession object have a key in the format of userId_dateString. However, if I want to get all the user's sessions from the last 7 days, I don't know how to do it in one query.
Any ideas?
I recommend to watch the video. It is told about the structuring of the data very well.
References to the playlist on the firebase 3
Firebase 3.0: Data Modelling
Firebase 3.0: Node Client
As I understand the principle firebase to use it effectively. Should be as small as possible to query the data and it does not matter how many requests.
But you will approach such a request. We'll have to add another field to the database "negativeDate".
This field allows you to get the last seven entries. Here's a video -
https://www.youtube.com/watch?v=nMR_JPfL4qg&feature=youtu.be&t=4m36s
.limitToLast(7) - 7 entries
.orderByChild('negativeDate') - sort by date
Example of a request:
const ref = firebase.database().ref('maxBenchPressSession');
ref.orderByChild('negativeDate').limitToLast(7).on('value', function(snap){ })
Then add the user, and it puts all of its sessions.
const ref = firebase.database().ref('maxBenchPressSession/' + userId);
ref.orderByChild('negativeDate').limitToLast(7).on('value', function(snap){ })

Resources