Reputation: 5828
I have a set of nodes with label Type. Some of them have relationships to other Type nodes and some of them do not. I want to loop through all of the Type nodes and do some action based on the relationship (whether it is null or has an existing relationship)
In pseudo code, this is what I want to do:
For each type1 in allTypes
For each type2 in allTypes
Match relationship between type1 and type2
If relationship between type1 and type2 exists
do something
else
do other thing
But I can't figure out how to do this in Cypher. I understand you can't do a MATCH inside a FOREACH statement in Cypher, so I'm trying with UNWIND like this:
MATCH (Types:Type)
WITH COLLECT(Types) AS types
UNWIND types as type1
UNWIND types as type2
MATCH (type1)-[r]->(type2)
RETURN type1.name,type(r), type2.name
This works fine for all the relationships that already exist, but when there is no relationship between type1 and type2, I'm not getting anything in my return result.
Upvotes: 0
Views: 2152
Reputation: 5047
How about using OPTIONAL MATCH
?
Some example data:
CREATE
(t1:Type {name:"t1"}),
(t2:Type {name:"t2"}),
(t3:Type {name:"t3"}),
(t1)-[:REL]->(t2)
The query:
MATCH (t1:Type)
OPTIONAL MATCH (t1)-[r]->(t2:Type)
RETURN
t1, t2,
CASE r
WHEN NULL THEN "other thing"
ELSE "something"
END AS info
The results:
╒══════════╤══════════╤═══════════╕
│t1 │t2 │info │
╞══════════╪══════════╪═══════════╡
│{name: t1}│{name: t2}│something │
├──────────┼──────────┼───────────┤
│{name: t2}│(null) │other thing│
├──────────┼──────────┼───────────┤
│{name: t3}│(null) │other thing│
└──────────┴──────────┴───────────┘
Upvotes: 3