Search code examples
cyphergraph-databasesmemgraphdbopencypher

What is the difference between two FOREACH block codes in Cypher?


Are these two blocks actually the same? The goal is to create three nodes with IDs 1, 2, 3, and 4.

Block 1:

FOREACH ( i IN [1, 2, 3, 4] | CREATE (n {id : i}) )

Block 2:

  CREATE (n { prop : [[1, 2], [3, 4]]);

  MATCH (n) FOREACH ( inner_list IN n.prop | FOREACH ( j IN inner_list | CREATE (u { prop : j }) ) );

The first method seems simpler to me, and I would go with that one. What would be the advantage of the second one?


Solution

  • The two queries here are clearly quite different. The second, which honestly looks very contrived and unnecessarily complex, creates an additional node, as well as changing the property name from id to prop. In reality, the alternative approach to the first query is much more likely to be something based on use of UNWIND. For example:

    UNWIND [1, 2, 3, 4] AS i
    CREATE (n {id: i})
    RETURN n
    

    I see no advantage to the second query other than as a demonstration of nested FOREACH clauses.