Indexing data in my firebase realtime database rules based on the nested value - firebase

I have the following JSON tree from my realtime database:
{
"old_characters" :
{
"Reptile" : {
"kick" : 20,
"punch" : 15
},
"Scorpion" : {
"kick" : 15,
"punch" : 10
},
"Sub-zero" : {
"kick" : 30,
"punch" : 10
}
},
"new_characters" : {
//...ect
}
}
Is it possible to set rules in my firebase console so that I can index my data based on the character with the highest value of kick?
The constraints are:
- character_name are dynamic.
- Key "kick" is static, but its value is dynamic.
Result should be:
Sub-zero first (kick 30)
Reptile second (kick 20)
Scorpion third (kick 15)

What you want seems to be a fairly simple Firebase query on the kick property:
var ref = firebase.dababase().ref('old_characters');
var query = ref.orderByChild('kick');
query.once(function(snapshot) {
snapshot.forEach(function(characterSnapshot) {
console.log(characterSnapshot.key);
console.log(characterSnapshot.child('kick').val());
});
});
You'll note that this prints the results in ascending order. You can:
either reverse the results client-side
or add an inverted property with -1 * score to each character and then order on that
To learn more about the inverting/sorting descending, have a look at some of these previous questions:
firebase -> date order reverse
Sorting in descending order in Firebase database
sorting numbers with firebase

Related

Get a filtered list from a terraform map of objects?

I have a list of users with characteristics like this and I want to create a local variable that includes the names of the users in the "maker" group.
variable "users" {
type = map(object({
groups = list(string)
}))
default = {
"kevin.mccallister" = {
groups = ["kids", "maker"],
},
"biff" = {
groups = ["kids", "teens", "bully"],
},
}
}
I want to write the local like this, but it complains
Error: Invalid 'for' expression ... Key expression is required when
building an object.
locals {
makers_list = flatten({
for user, attr in var.users: user
if contains(attr.groups, "makers")
})
}
How can I take that map of objects and get out a list of names based on group affiliation?
flatten() is not required for this. Also, the {} is pushing this to build an object. You can instead build a list using [] and then it will create a list of the users filtered by their group association.
makers_list = [
for user, attr in var.users: user
if contains(attr.groups, "makers")
]

Get an array of specific parameters from Image Collection of Google Earth Engine

I've got an Image Collection like:
ImageCollection : {
features : [
0 : {
type: Image,
id: MODIS/006/MOD11A1/2019_01_01,
properties : {
LST_Day_1km : 12345,
LST_Night_1km : 11223,
system:index : "2019-01-01",
system:asset_size: 764884189,
system:footprint: LinearRing,
system:time_end: 1546387200000,
system:time_start: 1546300800000
},
1 : { ... }
2 : { ... }
...
],
...
]
From this collection, how can I get an array of objects of specific properties? Like:
[
{
LST_Day_1km : 12345,
LST_Night_1km : 11223,
system:index : "2019-01-01"
},
{
LST_Day_1km : null,
LST_Night_1km : 11223,
system:index : "2019-01-02"
}
...
];
I tried ImageCollection.aggregate_array(property) but it allows only one parameter at one time.
The problem is that the length of "LST_Day_1km" is different from the length of "system:index" because "LST_Day_1km" includes empty values, so it's hard to combine arrays after get them separately.
Thanks in advance!
Whenever you want to extract data from a collection in Earth Engine, it is often a straightforward and efficient strategy to first arrange for the data to be present as a single property on the features/images of that collection, using map.
var wanted = ['LST_Day_1km', 'LST_Night_1km', 'system:index'];
var augmented = imageCollection.map(function (image) {
return image.set('dict', image.toDictionary(wanted));
});
Then, as you're already familiar with, just use aggregate_array to extract that property's values:
var list = augmented.aggregate_array('dict');
print(list);
Runnable complete example:
var imageCollection = ee.ImageCollection('MODIS/006/MOD11A1')
.filterDate('2019-01-01', '2019-01-07')
.map(function (image) {
// Fake values to match the question
return image.set('LST_Day_1km', 1).set('LST_Night_1km', 2)
});
print(imageCollection);
// Add a single property whose value is a dictionary containing
// all the properties we want.
var wanted = ['LST_Day_1km', 'LST_Night_1km', 'system:index'];
var augmented = imageCollection.map(function (image) {
return image.set('dict', image.toDictionary(wanted));
});
print(augmented.first());
// Extract that property.
var list = augmented.aggregate_array('dict');
print(list);
https://code.earthengine.google.com/ffe444339d484823108e23241db04629

React native concatenate instead of sum

I am creating an app using React Native and Firebase. Sample data from firebase is as below.
Sample Data (Firebase)
accountName:"Frimi"
accountType:"debit"
createdAt:March 24, 2020 at 7:05:56 PM UTC+5:30
initialAmount:2000
userId:"t7DJ##################"
username:"de#####"
From this data's I need to get the total amount of the initialAmount from several data's. I do this in react native as follows
Fetch Total (React Native)
fetchTotalAmount = () => {
const { accounts } = this.props
const uid = firebase.auth().currentUser.uid
return accounts && accounts.map((account) => {
let total = 0
return account.userId == uid ?
total += account.initialAmount : null
})
}
The problem here is instead of adding values I am getting concatenated string. I need to get sum of the initialAmount.
Try casting account.initialAmount to a Number like:
total += Number(account.initialAmount) : null
Look at this post for more casting references.

Why is this push() overwriting instead of adding?

I have a line of code inside a http callable Firebase Function that is supposed to add a new record to a spot in the Firebase Database.
return admin.database().ref('games/' + gameid + '/' + uid + '/logs/').push().set({guess: guess, result: pigs.toString() + 'P ' + bulls.toString() + 'B', score: score});
Here is an example entry in my database.
"games" : {
"39dba69c-f5a8-4e94-9553-d19372d43a92" : {
"1P0mWbp1jYOayaMEyQcnKvX4YB63" : {
"logs" : {
"-LDshYx2wJK6eT47_OVQ" : {
"guess" : "5647",
"result" : "1P 1B",
"score" : 450
}
},
"maxbulls" : 3,
"maxpigs" : 3,
"moves" : 6,
"score" : 450
},
"answer" : "2739dba69c41",
"id" : "39dba69c-f5a8-4e94-9553-d19372d43a92",
"requestor" : "1P0mWbp1jYOayaMEyQcnKvX4YB63",
"status" : "pending",
"turn" : ""
}
}
For some reason the set() is overwriting the record under logs (id of -LDshYx2wJK6eT47_OVQ). I want it to add a new record under logs with the auto-generated key from push(). I have used a very similar method before (with basically no differences) that worked as intended.
I have also tried changing set() to update() but it still overwrote. Is there something wrong with my path or database structure that I am overlooking? Thanks.

How can firebase 3 query or angularfire2 filter pipe used to display snapshot data in tabular format with sum/total

My firebase schema is as below:
{
"orders" : {
“-Shjy4X7atpPy12345Qum" : {
"qty" : 1,
"amount" : 10000,
"payment_type” : "Cash”,
"productId" : “-ShWSex7Hjit_mYrwuBA”,
"productPrice" : 13000,
"u_id" : “aABCW88eNIge4ysb9TDeTHESK4"
},
“-Ahjy6X9atpBy3435Hki” : {
"qty" : 1,
"amount" : 20000,
"payment_type” : "Card”,
"productId" : “-AhWFet9Hjit_mGrwuPA”,
"productPrice" : 13000,
"u_id" : “aABCW88eNIge4ysb9TDeTHESK4"
}
}
}
Desired output:
Orders
Product--------------------Quantity---------------Price
-ShWSex7Hjit_mYrwuBA------- 1 ---------------10000
-AhWFet9Hjit_mGrwuPA------- 1 ---------------10000
Grand Total : 20000
Can this be achieved in Firebase query:
{ query: {orderByChild: 'productId', equalTo: 'productId'}
or by using angular pipes ?
Solution is appreciated.
I can suggest one improvement in your DB schema to make it easier. Since a order can contain multiple products, maybe you can create a node under orders called "cart" which will have Key-Value pairs of productId (as key) and quantity (as value).
{
orders:
cart:
productId_1 : quantity_1,
productId_2 : quantity_2,
}
Now you can just read the "cart" node & each object of that node will have $key as productId - use that to retrieve price of the product. and $value is the quantity. Now you have all values you need.

Resources