cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

How to query multiple relationships in Cypher

Hello Everyone,
I am new to Cypher and having issues while querying for multiple relationships. I have two relationships :abc and :xyz. I want to get all the nodes that are 2 hops away which have either :abc OR :xyz relationships. Also, :abc is directional, whereas :xyz is bidirectional.
I tried

MATCH(n)-[:abc*1..2]->(m),
(m)-[:xyz*1..2]-(o)
RETURN n, m, o

But, it gives the result with AND condition and hence the nodes which do not have :xyz relations are not included. How can I solve it?
Thanks in advance.

1 ACCEPTED SOLUTION

You can use the following pattern to query for relationships that have one of several relationships;

()-[:X|Y|Z]-()

Using match (n)-[:abc|xyz]-() would not work in your case because you could get paths with the wrong direction for the 'abc' relationship type.

If your requirement is paths of length 2 that consist of relationships with type either 'abc' or 'xyz', then the only combinations are the following permutations:

()-[:abc]->()-[:abc]->()
()-[:xyz]-()-[:xyz]-()
()-[:abc]->()-[:xyz]-()
()-[:xyz]-()-[:abc]->()

I think the following query will provide this. I am assuming the direction of the 'abc' relationships are the same.

MATCH p=()-[:abc0..1]->()-[:xyz0..2]-()-[:abc*0..1]->()
WHERE length(p) = 2
RETURN nodes(p) as nodes

Sorry I don't have any data to fully test it.

View solution in original post

1 REPLY 1

You can use the following pattern to query for relationships that have one of several relationships;

()-[:X|Y|Z]-()

Using match (n)-[:abc|xyz]-() would not work in your case because you could get paths with the wrong direction for the 'abc' relationship type.

If your requirement is paths of length 2 that consist of relationships with type either 'abc' or 'xyz', then the only combinations are the following permutations:

()-[:abc]->()-[:abc]->()
()-[:xyz]-()-[:xyz]-()
()-[:abc]->()-[:xyz]-()
()-[:xyz]-()-[:abc]->()

I think the following query will provide this. I am assuming the direction of the 'abc' relationships are the same.

MATCH p=()-[:abc0..1]->()-[:xyz0..2]-()-[:abc*0..1]->()
WHERE length(p) = 2
RETURN nodes(p) as nodes

Sorry I don't have any data to fully test it.