7

I want to do something like this in cypher:

MATCH (n:node) WHERE n.ID = x        //x is an integer value
FOREACH (num in n.IDs: 
    MATCH (p:node) WHERE p.ID = num
    CREATE (n)-[:LINK]->(p) )

where num is an array of integer values referring to the IDs of nodes that need to be linked to the node matched in the first line.

When I run this query, I get the error: Invalid use of MATCH inside FOREACH.

I'm in the early stages of teaching myself both Cypher and Neo4j. How can I achieve my desired functionality here? Or am I barking up the wrong tree - am I failing to grasp something that makes it unnecessary for me to do so?

drew moore
  • 31,565
  • 17
  • 75
  • 112

1 Answers1

11

This is not allowed, instead use the top-level MATCH like http://gist.neo4j.org/?8332363

MATCH (n:node), (p:node)
WHERE n.ID = 1 AND p.ID in [2,3,4]
CREATE (n)-[:LINK]->(p)
Peter Neubauer
  • 6,311
  • 1
  • 21
  • 24
  • If there is a number M(denotes some count) then how can we achieve p.ID in [2 to M] – GvanJoic Jan 09 '15 at 17:26
  • 3
    This ought to be in the documentation for FOREACH, imho. foreach-then-match is a common idiom in many languages so it would be great to have it called out that the Cypher way is different! – Noah Sussman Jul 28 '15 at 16:48
  • Link in the answer produces "Resource not found" – alan Aug 29 '19 at 17:25