Fetch only values from neo4j database - reactjs

I am trying to fetch some data from my neo4j database and show in a list for auto suggestion in reactjs application. I have following codes to fetch the data.
let result = null;
try {
result = await session.run(
'MATCH (n:Person) RETURN properties(n)',
)} finally {
await session.close()
}
await driver.close()
Here the Person nodes have different properties, i.e. all the Person nodes do not have same properties. some have editor name, others have author name. What i want to do is fetching only values without keys and assigning them in an array. here
'MATCH (n:Person) RETURN properties(n)'
returns
{
"myName": "myname 1",
"hisName": "myname 2"
}
{
"herName": "myname 3",
"theirName": "myname 4"
}
And 'MATCH (n:Person) RETURN keys(n)' returns
["myName"]
["hisName"]
["herName"]
["theirName"]
But i want to fetch only values [myname 1, myname 2, myname 3, myname 4]
Could you please tell me how to fetch only values ?
Also how to keep those values in an array ?

This is how to get all values for the key myName in Person class.
Check if the node has this property using EXISTS
Put the values in an array using "COLLECT".
MATCH (n:Person)
WHERE EXISTS(n.myName)
RETURN collect(distinct n.myName)
Sample result:
["Zhen", "Praveena", "Michael", "Arya", "Karin", "Adam", "John", "mary", "jack", "david", "tom"]

This will work.
MATCH(n:Person)
RETURN apoc.coll.flatten(COLLECT(EXTRACT(key IN keys(n) | n[key])))
p.s. Sorry, EXTRACT() has been deprecated. Below is better.
MATCH(n:Shima)
RETURN apoc.coll.flatten(COLLECT([key IN keys(n) | n[key]]))

Related

How to add a new map field inside a parent map field in Firestore?

I want to add a new map field inside another map field.
My data structure looks like this:
I want to add a 'field b' after 'field a' inside 'Filed 1' (pardon my typo).
my code looks like this
const collsRef = doc(db, "collections", collectionUid); // get the right document
await setDoc(collsRef, { sellectData }, { merge: true });
but not only this is giving me an error, I believe this code would only add a new field at the same level as 'Filed 1'
the data type triggering the unsupported field value error is an JS object like so – do I need to parse it before comiting it to the db?
I've blanked out data and left the structure and syntax because it contained personal sensitive data. I hope it's enough to explain the problem.
many thanks in advance
I'm not sure what the sellectData structure looks like but you have to construct an object that has the same structure from Firestore. See sample code below:
const collsRef = doc(db, "collections", collectionUid);
let sellectData = {
"field b": { "key b" : "value b" }
}
await setDoc(collsRef, {
"Filed 1": sellectData
}, { merge: true });
This would result in (already corrected your typo):
Update:
You have two options to set the object key as a variable.
You need to make the object first, then use [] to set it.:
let key = "Field 1";
let sellectData = {
"field b": { "key b" : "value b" }
}
await setDoc(collsRef, {
[key]: sellectData
}, { merge: true });
Or, by contructing the object itself.
let key = "Field 1";
let sellectData = {
[key] : { "field b":
{ "key b" : "value b" }
}
}
// Remove the curly brackets `{}` in this case.
await setDoc(collsRef,
sellectData,
{ merge: true });
For more information, see Update fields in nested objects.

How to find an item in an object of array

I have a list of IDs. Also I have an object that has arrays of datas like the below structure.
[
foods(
foodId: 345,
category: 10,
tools: [10],
name: "food name 1"
),
foods(
foodId: 191,
category: 4,
tools: [2],
name: "food name 2"
),
]
In my list I have list [345, 191]
I want to have a mechanism to access the information of the object when I provide a foodId.
I made it work with one inner and one outer loop. But I was wondering if there is an easier way to do it:
ForEach(foodDetails, id: \.self){ item in
ForEach(self.foods.datas){ ex in
if(ex.foodId == item){
Text(ex.name)
}
}
Any idea how to make it work?
Thanks in advance
you can do simply by getting first element where id match
let result = foodDetails.first(where: {$0.foodId == id})
if let food = result {
print(food.name ?? "") //if name is optional
print(food.foodId)
print(food.category)
}
result you got is that foods? optional struct which have this id

Remove duplicate content from array

"name": [
{
"name": "test1"
},
{
"name": "test2"
},
{
"name": "test3"
},
{
"name": "test1"
},
]
I have the above created by nodejs. During array push, I would like to remove duplicated arrays from the list or only push the name array if the individual array does not exist.
I have tried below codes but it changes the array.
var new = [];
for (var i =0;i<name.length;i++){
new['name'] = name[i].name;
}
The easiest way is probably with Array.prototype.reduce. Something along these lines, given your data structure:
obj.name = Object.values(obj.name.reduce((accumulator, current) => {
if (!accumulator[current.name]) {
accumulator[current.name] = current
}
return accumulator
}, {}));
The reduce creates an object that has keys off the item name, which makes sure that you only have unique names. Then I use Object.values() to turn it back into a regular array of objects like in your data sample.
the solution can be using temp Set;
const tmpSet = new Set();
someObj.name.filter((o)=>{
const has = tmpSet.has(o.name);
tmp.add(o.name);
return has;
});
the filter function iterating over someObj.name field and filter it in place if you return "true". So you check if it exists in a tmp Set & add current value to Set to keep track of duplicates.
PS: new is a reserved word in js;
This should do it
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
https://wsvincent.com/javascript-remove-duplicates-array/

Infinite loop on JS for

My code stays in the second for forever, testing the same category every step and decrementing every time.
I have two arrays, one of them is called categoriesToUpdate and is a list of category ids (string values) for categories that I have to update, and the other is called categories, containing all the actual category data I'm working with.
I have to test if the id value for a category that I have to update is the same as the database and if it is, decrement the attribute position of its object and update the database. But it is infinitely decrementing the bank.
let newCategory;
let name;
let position;
for(let id of categoriesToUpdate) {
for(let cat of categories) {
if(id === cat.id) {
position = cat.category.category.lastPosition - 1;
name = cat.category.category.categoryName;
newCategory = {
category: {
categoryName: name,
lastPosition: position,
}
}
cRef.child(id).update(newCategory);
}
}
}
Examples of the two arrays:
categoriesToUpdate = ['-lGz4j77...', '-uEbKO3...', ...]
and
categories = [
{
category: {
category: {
categoryName: "name",
lastPosition: "number",
}
},
id: "category id";
},
{
...
}
]
it is difficult to explain how I get the arrays, but basically, categoriesToUpdate is an array of ids that I add to my logic, I have to do update in each of these categoriesand categories is an array that has all categories of the database, comes from Firebase.
let id of categoriesToUpdate. I'm assuming categoriesToUpdate is an array of Category objects. So id is actually a Category object. To compare it should be id.id === cat.id.
Also you can try filter instead of a second loop.
Something like
var matched = categories.filter(c => c.id === id.id)[0];
Then compare matched. Nested loops are hard to read, imo.

How to re-structure the below JSON data which is a result set of SQL query using cursors in python

def query_db(query, args=(), one=False):
cur = connection.cursor()
cur.execute(query, args)
r = [dict((cur.description[i][0], value)
for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return (r[0] if r else None) if one else r
my_query = query_db("select top 1 email as email_address,status = 'subscribed',firstname,lasstname from users")
json_output = json.dumps(my_query)
print json_output
Result is this:
[{
"status": "subscribed",
"lastname": "Engineer",
"email": "theengineer#yahoo.com",
"firstname": "The"}]
what I want is this
{
"email_address":"yash#yahoo.com",
"status":"subscribed",
'merge_fields': {
'firstname': 'yash',
'lastname': 'chakka',
}
I don't have any column called merge-fields in database but, I want this merge-fields header for every email-id with first name and last name under it to post it to Mailchimp. what modification do i have to do to my cursor get desired output. Any help will be appreciated. Thanks!
I'm adding this so that future users of mailchimp API version3 can get an idea of how I achieved this.
Here is what i did I've added another function which accepts values in other word I capture all the values which are resulted from myquery and pass it to this below function
def get_users_mc_format(query):
users = query_db(query)
new_list = []
for user in users:
new_list.append({
"email_address": user["email"],
"status": user["status"],
"merge_fields": {
"FNAME": user["firstname"],
"LNAME": user["lastname"],
},
"interests": {
"1b0896641e": bool(user["hardware"]),
}
})
return new_list

Resources