Why is this push() overwriting instead of adding? - firebase

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.

Related

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

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

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

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.

Filtering / Querying by the Contents of a List in DynamoDB

I am attempting to filter a DynamoDB query by the contents of a Map contained within a List. Here's an example of the structure I'm dealing with.
{
'EventType': 'git/push'
'EventTime': 1416251010,
'Commits': [
{
'id': '29d02aff...',
'subject': 'Add the thing to the place'
},
{
'id': '9d888fec...',
'subject': 'Spelling errors'
},
...
]
}
The hash key is EventType and range key EventTime. I am trying to write a filter that filters the result of a query to a specific id. Is is possible to create a DynamoDB filter expression that correctly filters the query like this? (My first thought was to use contains (a, a), but I don't think that will work on a List of Maps.)
This isn't currently supported by DynamoDB's API's expression language (as of November 2014) but there are some workarounds mentioned here.
I found a solution and I tested it, and it is working fine.
Here's what I did,
// created a schema like that:
var Movie = dynamo.define('example-nested-attribute', {
hashKey : 'title',
timestamps : true,
schema : {
title : Joi.string(),
releaseYear : Joi.number(),
tags : dynamo.types.stringSet(),
director : Joi.object().keys({
firstName : Joi.string(),
lastName : Joi.string(),
titles : Joi.array()
}),
actors : Joi.array().items(Joi.object().keys({
firstName : Joi.string(),
lastName : Joi.string(),
titles : Joi.array()
}))
}
});
and then you can query of a nested array of objects:
var params = {};
params.UpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag';
params.ConditionExpression = '#year = :current';
params.ExpressionAttributeNames = {
'#year' : 'releaseYear',
'#dir' : 'director',
'#act' : 'actors'
};
params.ExpressionAttributeValues = {
':inc' : 1,
':current' : 2001,
':title' : ['The Man'],
':firstName' : 'Rob',
':tag' : dynamo.Set(['Sports', 'Horror'], 'S')
};

ElasticSearch - Range filter by date is not working,

I'm trying to filter a query using range by date but it's not working. If i use gt, gte, lt, lte it returns zero results. If i use only gt or lt, it returns some results but the filter is not working.
I've checked datatype on uri http://mydomain.local:9200/logstash-2014.09.09/_mapping?pretty=true the field type is correct:
"original" : {
"type" : "date",
"format" : "dateOptionalTime"
}
Here is an example of a result that i have indexed in ElasticSearch:
{
"_index" : "logstash-2014.09.08",
"_type" : "iis",
"_id" : "wxtnfpyjR4u7dhwlEAWevw",
"_score" : 1.0,
"_source":{"#version":"1","#timestamp":"2014-09-08T20:55:46.460Z",
"type":"iis","original":"14-09-08 17:39:58"}
}
And here is how i'm trying to perform a query:
{
"query" : {
"filtered" : {
"filter" : {
"range" : {
"original" : {
"gt" : "14-09-10"
}
}
}
}
}
}
Anyone knows what is wrong on my query? Why it returns some results if i don't have any date greater than today ( 2014-09-09 )?
I created an index with the same mapping and tried to put a record in
curl -XPOST localhost:9200/test-1/x/_index -d '{"original": "14-09-08 17:39:58"}'
and got an error:
{"error":"MapperParsingException[failed to parse [original]]; nested: MapperParsingException[failed to parse date field [14-09-08 17:39:58], tried both date format [dateOptionalTime], and timestamp number with locale []]; nested: IllegalArgumentException[Invalid format: \"14-09-08 17:39:58\" is malformed at \" 17:39:58\"]; ","status":400}`
So I believe that you are in a a locale where that ##-##-## is being interpreted as something other than yy-mm-dd.
You are using Logstash so you can fix the original field before it goes in with a mutate to make it unambiguous.
mutate {
replace => { original => "20%{original}" }
}

Resources