Neo4j query for relationship

(Pappu Setrosoft) #1

Hello guys, i have existing five node with same label and i want to create one other node and also create a relation with all existing five node i was try but its create one to one relation on one to many relation. please help.

match (e:video) create(v:videomaster{name:'videomaster'}),
(e)-[r:DO_SHOPPING_WITH ]->(v)

see screen sort

But i want to like this at creation time of node

(Pappu Setrosoft) #2

MATCH p = (u:user)
merge (v:u_master{name:"usermaster"})
FOREACH (n IN nodes(p)| merge(n)-[r:test]->(v))

(Andrew Bowman) #3

While that works, that's more complicated than it needs to be. You can shorten this to:

MATCH (u:user)
MERGE (v:u_master{name:"usermaster"})
MERGE (n)-[r:test]->(v)

The idea is that after the match in the first line, you have a number of rows of results, one per u node. Then for each of those rows, MERGE executes to create the v node (only the first of those merges creates the node, the others match to that just-created node). The last line then executes and the relationship is created between each u node and the v node.

That said, it would be a bit more efficient to reorder the query instead:

MERGE (v:u_master{name:"usermaster"})
MATCH (u:user)
MERGE (n)-[r:test]->(v)

With this, the single v node is created (or matched to if it already existed). Then we match to the u nodes (each one will have the same v on its row). Then the relationships are merged between them.