问题
I have to summarize values in firebase database.
Note: this is a simplified non real project to make it easier to explain. So apologize if the JSON data has an error. It is for demonstration purposes and I will adjust to my real needs. Full project description with real data is here: best practize summarize FirebaseDatabase values, but seems too specific.
Assuming I collect weight data for multiple cars, every time they are on the scale.
So some sample data could look like:
weightTable{
weightKey1{
"carKey" : "carOne",
"carWeight" : 1.4
},
weightKey2{
"carKey" : "carOne",
"carWeight" : 1.9
},
weightKey3{
"carKey" : "carTwo",
"carWeight" : 1.1
},
weightKey4{
"carKey" : "carThree",
"carWeight" : 1.7
}
}
I now want to have a separate "table" where I only have the summary of all the weight data, grouped by "carKey".
So I get
summTable{
"carOne"{
"weightSum" : 3.3,
"cnt" : 2
},
"carTwo"{
"weightSum" : 1.1,
"cnt" : 1
},
"carThree"{
"weightSum" : 1.7,
"cnt" : 1
}
}
"weightSum" is the summary of "carWeight".
"cnt" is the count of data summarized.
Finally I want to have a table, that list the summary of all cars
totalCarWeight{
"weightSum" : 6,1,
"cnt" : 4
}
sumTable is used to populate view in an Android app and webpage to display the summary. If they click on a car in the summary, they get the detailed view for this car, with each weight collected. So summary data should be up to date on best effort base.
Possible Issues I see:
Device has no network connectivity and adds data to the "weightTable";
Multiple device add data to the "weightTable".
Any hints how to do this ?
On a normal SQL database we can ask the database to make a summary or count entries in a query.
Hope this is easier to understand and answer now.
Some guidance in either Android or javascript would be great.
回答1:
You can query Firebase over the "weightTable" where "carKey" equalTo "carOne" and sum values in your app.
For AngularFire querying see: docs
For Firebase SDK (web) see sorting and filtering section of: docs
If you still need other tables ("summTables", "totalCarWeight") you will need to update them everytime you write to "weightTable" - so you can do it in your app or (maybe better way) use Google Cloud Functions for Firebase. So everytime you write to "weightTable" it will fire function that updates other tables.
For Google Cloud Functions for Firebase see: Jen Person video and her other videos on Firebase YT channel.
来源:https://stackoverflow.com/questions/42044795/how-to-summarize-values-in-firebase-database-askfirebase