Iterate over list of objects and create nodes by properties of objects Neo4j

Viewed 341

I have a list of objects, the objects have different properties.

array = [{name: 'Armen', age: 26}, {name: 'Alex', profession: 'Scientist'}]

I need to iterate over list and create nodes with properties provided by objects. Which is the easiest and best practice way to do it? Thanks in advance! I have tried to use unwind both for list and object keys

WITH array AS nodes 
UNWIND nodes AS node
UNWIND keys(node) AS prop 
WITH node, prop
MERGE (man: Man {prop:node[prop]}) 
RETURN man

but in this case I get one node for each property.

2 Answers

Unwinding prop will result in separate rows for each property and that is why it doesn't work. You can keep the properties in one collection like this,

WITH [{name: 'Armen', age: 26}, {name: 'Alex', profession: 'Scientist'}] AS nodes 
UNWIND nodes AS node
WITH node, properties(node) as props
MERGE (man:Man {name: props.name}) ON CREATE SET man += props
RETURN man

(i'm assuming that name is common to all items)

As @aldrin and Cobra from Neo4j Community showed, I can add properties with SET. Here is the easiest way I found to do it.

WITH [{name: 'Armen', age: 26}, {name: 'Alex', profession: 'Scientist'}] 
AS nodes 
UNWIND nodes AS node
CREATE (man:Man)
SET man += node 
RETURN man

I added Ids to my nodes so I can create and update nodes by just one query.

WITH [{id: 0, name: 'Armen', age: 26}, {id: 1, name: 'Alex', profession: 'Scientist'}] AS nodes 
UNWIND nodes AS node
MERGE (man:Man {id: node.id})
SET man += node 
RETURN man
Related