How to load Firebase data to Graph Entity? Is there a way to modal the data? With Swift 3 - cosmicmind

I'm new to CosmicMind and have questions about the data process.
In the CosmicMind CardTableView Sample, the data are read from SampleData of Entity type.
Q1: Is there a way I can load my Firebase Data to Entity? And if so, how to do it? Looks like shouldn't be difficult, as it's JSON already. I'm using Swift 3.2
Q2: Is there a way to modal the Entity?
Thanks a lot!!

Welcome to CosmicMind :)
The easiest way would be to create an import function that takes in your JSON data and maps the key value pairs to properties in an Entity. If there is a type specifier in Firebase, then you can set that as the Entity type. I don't use Firebase, so I can't describe the setup 100%, but here is an example of what you would do, assuming Firebase gives you a unique ID.
func importFirebase(data: [[String: Any]]) {
let graph = Graph()
let search = Search<Entity>(graph: graph).for(types: "User")
let users = search.sync()
var index = [Int: Entity]()
for user in users {
if let id = user["id"] as? Int {
index[id] = user
}
}
for json in data {
if let id = json["id"] as? Int {
var entity: Entity
if nil == index[id] {
entity = Entity(type: "User")
} else {
entity = index[id]!
}
for (k, v) in json {
entity[k] = v
}
}
}
graph.sync()
}
let data = [
["type": "User", "id": 1, "name": "Daniel", "age": 33],
["type": "User", "id": 2, "name": "Adam", "age": 28],
["type": "User", "id": 3, "name": "Sarah", "age": 23]
]
importFirebase(data: data)
This is not necessarily the optimal solution, it should give you an idea though.
Hope it helps, all the best!

Related

How to filter object by their child in Google Cloud Realtime Database?

So, I've Google Cloud Firebase Realtime Database, where objects stored and identified by their unique IDs. I need to filter them by their child property, for example, called surname where it would be exact match and get result of the whole object from promise. How to do that?
Example of how database looks like:
{
"uniqueID123": {
"surname": "some surname",
"data": "123"
},
"anotheruniqueID": {
"surname": "some another surname",
"data": "info"
}
}
To order and filter data you can use a query, like this:
const ref = db.ref('theParentNodeOfYourJSON');
ref.orderByChild('surname').equalTo("some surname").on('value', (snapshot) => {
snapshot.forEach((child) => {
console.log(snapshot.key, snapshot.child("surname").val());
})
});

How can I automatically append a property from a relation to the root object?

How can I automatically append a property from a relation to the root object, as if it were a column from the same table but actually it is coming from another table.
Supose I have an User model that hasMany Emails.
How can I only append the email from the first Email of the User model, so that everytime I query the User model I get it like a property?
Example:
What I'm doing:
(await User.query().where('id', id).with('emails').first()).toJSON()
{
"name": "Eleandro Duzentos",
"emails": [
{ "email": "eleandro#inbox.ru" },
{ "email": "eleandro#mail.ru" }
]
}
What I want:
(await User.find(id)).toJSON()
{
"name": "Eleandro Duzentos",
"email": "eleandro#inbox.ru"
}
Obs: I'm not putting the email on the same table because, there's a chance that a user may need more then one email in a long future, but for now, it has only one.
How can I do that?
For the customized JSON response i would suggest the use of serializers.
You can override the default serializers to get the desired result.
You can refer to this - https://adonisjs.com/docs/4.0/serializers
Here is my code. You could be inspired by it:
Model User:
...
const Email = use('App/Models/Email')
class User extends Model {
async getEmails() {
let list = []
let emails = await Email.query().where('user_id', this.id).fetch()
emails.rows.forEach(email => {
list.push({ name: this.username, email: email.email })
});
return list
}
emails() {
return this.hasMany('App/Models/Email')
}
}
module.exports = User
Controller :
...
let user = await User.find(1)
return await user.getEmails()
Output :
[
{"name":"CrBast","email":"test#crbast.ch"},
{"name":"CrBast","email":"test2#crbast.ch"}
]
Feel free to correct me if that's not what you want :)

NodeJS Iterate through City in JSON, Return Cities and Users in each City

I have the below snippet from a JSON Object that has 3,500 records in it.
[
{
"use:firstName": "Bob",
"use:lastName": "Smith",
"use:categoryId": 36,
"use:company": "BobSmith",
"use:webExId": "Bob.Smith#email.com",
"use:address": {
"com:addressType": "PERSONAL",
"com:city": "US-TX",
"com:country": 1
}
},
{
"use:firstName": "Jane",
"use:lastName": "Doe",
"use:categoryId": 36,
"use:webExId": "Jane.Doe#email.com",
"use:address": {
"com:addressType": "PERSONAL",
"com:city": "US-CA",
"com:country": "1_1"
}
}
{
"use:firstName": "Sam",
"use:lastName": "Sneed",
"use:categoryId": 36,
"use:webExId": "Sam.Sneed#email.com",
"use:address": {
"com:addressType": "PERSONAL",
"com:city": "US-CA",
"com:country": "1_1"
}
}
]
I am using NodeJS and I have been stuck on figuring out the best way to:
1. Iterate through ['use:address']['com:city' to map out and identify all of the Cities. (In the example above, I have two: US-TX and US-CA in the three records provided)
2. Then identify how many records match each City (In the example above, I would have US-TX: 1 and US-CA: 2)
The only code I have is the easy part which is doing a forEach loop through the JSON data, defining userCity variable (to make it easier for me) and then logging to console the results (which is really unnecessary but I did it to confirm I was looping through JSON properly).
function test() {
const webexSiteUserListJson = fs.readFileSync('./src/db/webexSiteUserDetail.json');
const webexSiteUsers = JSON.parse(webexSiteUserListJson);
webexSiteUsers.forEach((userDetails) => {
let userCity = userDetails['use:address']['com:city'];
console.log(userCity);
})
};
I've been searching endlessly for help on the topic and probably not formulating my question properly. Any suggestions are appreciated on how to:
1. Iterate through ['use:address']['com:city' to map out and identify all of the Cities.
2. Then identify how many records match each City (In the example above, I would have US-TX: 1 and US-CA: 2)
Thank you!
You could reduce the webexSiteUsers array into an object that is keyed by city, where each value is the number of times the city occurs. Something like the below should work.
const counts = webexSiteUsers.reduce((countMemo, userDetails) => {
let userCity = userDetails['use:address']['com:city'];
if (countMemo[userCity]) {
countMemo[userCity] = countMemo[userCity] + 1;
} else {
countMemo[userCity] = 1;
}
return countMemo;
}, {});
counts will then be an object that looks like this.
{
"US-TX": 1,
"US-CA": 2
}

Query CosmosDb Unstructured JSON

How can CosmosDB Query the values of the properties within a dynamic JSON?
The app allows storing a JSON as a set of custom properties for an object. They are serialized and stored in CosmosDb. For example, here are two entries:
{
"id": "ade9f2d6-fff6-4993-8473-a2af40f071f4",
...
"Properties": {
"fn": "Ernest",
"ln": "Hemingway",
"a_book": "The Old Man and the Sea"
},
...
}
and
{
"id": "23cb9d4c-da56-40ec-9fbe-7f5178a92a4f",
...
"Properties": {
"First Name": "Salvador",
"Last Name": "Dali",
"Period": "Surrealism"
},
...
}
How can the query be structured so that it searches in the values of Properties?
I’m looking for something that doesn’t involve the name of the
sub-propety, like SELECT * FROM c WHERE
some_function_here(c.Properties, ‘Ernest’)
Maybe I get your idea that you want to filter the documents by the value of the Properties, not the name. If so , you could use UDF in cosmos db.
sample udf:
function query(Properties,filedValue){
for(var k in Properties){
if(Properties[k] == filedValue)
return true;
}
return false;
}
sample query:
SELECT c.id FROM c where udf.query(c.Properties,'Ernest')
output:
Just summary here, Ovi's udf function like:
function QueryProperties (Properties, filedValue) {
for (var k in Properties) {
if (Properties[k] && Properties[k].toString().toUpperCase().includes(filedValue.toString().toUpperCase()))
return true;
return false;
}
Both of the following syntax's will work.
SELECT * FROM c where c.Properties["First Name"] = 'Salvador'
SELECT * FROM c where c.Properties.fn = 'Ernest'

Azure Stream Analytics convert array values

Very specific question, if I have the following input in my Streaming Analytics component:
//some input
"outputs": [
{
"name": "output1",
"unit": "unit1",
"value": "95813"
},
{
"name": "output2",
"unit": "unit2",
"value": "303883"
}, // and more array values
How can I get a JSON result that would look as follows:
"outputs":[ {
"output1":95813,
"output2":303883
//etc
}]
So, I don't need the unit value, and to save space, I'd like to use the 'name' as the key, and the 'value' as the value of the key-value array.
This is my current query:
SELECT
input.outputs as outputs
INTO "to-mongodb"
FROM "from-iothub" input
but this of course creates seperate JSON arrays, with the same structure as I do get as my input.
Anyone any idea on how to do this?
In worst case, just filtering out the 'unit' would also already be a great help.
Thanks in advance
You could use user-defined functions in Azure Stream Analytics. Please refer to the sample function I tested for you.
UDF:
function main(arg) {
var array = arg.outputs;
var returnJson = {};
var outputArray = [];
var map = {};
for(var i=0;i<array.length;i++){
var key=array[i].name;
map[key] = array[i].value;
}
outputArray.push(map);
returnJson = {"outputs" : outputArray};
return returnJson;
}
Query:
WITH
c AS
(
SELECT
udf.processArray(jsoninput) as result
from jsoninput
)
SELECT
c.result
INTO
jaycosmostest
FROM
c
Test Output:
Hope it helps you.

Resources