Neo4j 2.0 Cypher Query - CREATE within a FOREACH

1,636 views
Skip to first unread message

Rory Madden

unread,
Aug 4, 2013, 7:50:14 AM8/4/13
to ne...@googlegroups.com
I'm having trouble with a cypher query. I want to replace one or more relationships, if they exists, with a new node and two new relationships. The query below tests if the relationship exists but it fails on the new node creation. The CREATE syntax works on its own but not nested within the FOREACH loop.

START s = node(1)
MATCH (u)-[r?:RELATED]->(s)
FOREACH (u in (CASE WHEN r<>NULL THEN [u] ELSE [] END):
CREATE (u)<-[:REL1]-(n {test:"test"})-[:REL2]->(s))
DELETE r
RETURN s

I get an error saying: Unknown identifier n

Does anyone know how to fix this?

Andres Taylor

unread,
Aug 4, 2013, 10:09:00 AM8/4/13
to neo4j
Hi Rory,

I would do it like this:

START s = node(1) 
MATCH (u)-[r?:RELATED]-(s) 
DELETE r 
WITH collect(u) AS collectionOfU, s 
FOREACH (u IN collectionOfU : 
  CREATE (u)<-[:REL1]-({ test:"test" })-[:REL2]->(s)) 
RETURN s

The aggregate function COLLECT does what you are looking for - it creates a collection of the incoming values, ignoring any nulls.

Don't know why you are getting that weird error message - but we did have a bug around this some time ago. Have you tried on the latest stable version?

Andrés


--
You received this message because you are subscribed to the Google Groups "Neo4j" group.
To unsubscribe from this group and stop receiving emails from it, send an email to neo4j+un...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
The best way to ask for Cypher help: http://console.neo4j.org/usage.html 

Michael Hunger

unread,
Aug 4, 2013, 3:18:29 PM8/4/13
to ne...@googlegroups.com
Also if you don't need the return results at all you can get by by using something much simpler:

START s = node(1)
MATCH (u)-[r:RELATED]->(s)
DELETE r
CREATE (u)<-[:REL1]-(n {test:"test"})-[:REL2]->(s))

Rory Madden

unread,
Aug 11, 2013, 6:59:19 AM8/11/13
to ne...@googlegroups.com
Thanks for your responses. This helped me to sort out the problem.
Reply all
Reply to author
Forward
0 new messages