How to chain UNWIND clauses

cypher

(Johanringmann) #1

I am attempting to use two separate lists to create nodes/relationships in cypher.

My current solution is:

MERGE (t:Test)
WITH t
UNWIND ["a","b"] AS name                      // first list
MERGE (t)-[:FOO_REL]->(a:Foo { name: name })
WITH DISTINCT t
UNWIND [100,200] AS id                        // second list
MERGE (t)-[:BAR_REL]->(b:Bar { id: id })

This works as long as both lists have entries in them. However, if the first list is empty then the second list is never unwound (and no :Bar nodes are created).

How would I go about chaining UNWIND s such that I can create nodes/relationships from two separate lists in a single query?


(Johanringmann) #2

I ended up using FOREACH instead of UNWIND . Since this uses parentheses around the inner query, they are clearly delimited from eachother:

MERGE (t:Test)
FOREACH (name in ["a","b"] | 
  MERGE (t)-[:FOO_REL]->(a:Foo { name: name })
)
FOREACH (id in [100,200] |
  MERGE (t)-[:BAR_REL]->(b:Bar { id: id })
)

(Andrew Bowman) #3

Using FOREACH is the quicker solution for this.

If you needed to use UNWIND, we do have some documentation on this effect (as this is a cartesian product of each row with each element of the list on the row, an empty list means the row is wiped out, since it's a x 0), as well as a workaround (using CASE to unwind [null] instead, the single null element will ensure the row stays).