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.

Direct and indirect relationships of same type without union

I have a general question regarding the optimization of queries which retrieve directly and indirectly related nodes of the same type. Currently I use a union query to achieve this. As an example lets say I want all roles for a user. The user can have a role directly assign with a HAS_ROLE relationship or he can have a role indirectly assign, e.g. through (user)-[:IN_GRP]->()->[:HAS_ROLE]->(role). Here's an example of how I would do it with union:

MATCH (a:User { name: 'xyz' })-[:IN_GROUP]->(b)-[:HAS_ROLE]->(c:Role)
RETURN c as role
UNION ALL MATCH (a:User { name: 'xyz' })-[:HAS_ROLE]->(d:Role)
RETURN d as role

I wonder if there is a way to achieve the same result without a union?

1 ACCEPTED SOLUTION

MuddyBootsCode
Graph Steward

If you're trying to do this without a union you might be able to get away with something like this:

MATCH (a:User { name: 'xyz' })-[g:IN_GROUP]->(b)-[:HAS_ROLE]->(c:Role)
with c, where not (a)-[g]->(b)
MATCH(a:User {name: 'xyz'})-[:HAS_ROLE]->(r:Role)
with collect(c) + collect(r) as roles
return roles

I don't have your data set to test it on but that is more or less how you could go about this without a union. Although I think you'd find doing it with a union a little more straight forward.

View solution in original post

2 REPLIES 2

MuddyBootsCode
Graph Steward

If you're trying to do this without a union you might be able to get away with something like this:

MATCH (a:User { name: 'xyz' })-[g:IN_GROUP]->(b)-[:HAS_ROLE]->(c:Role)
with c, where not (a)-[g]->(b)
MATCH(a:User {name: 'xyz'})-[:HAS_ROLE]->(r:Role)
with collect(c) + collect(r) as roles
return roles

I don't have your data set to test it on but that is more or less how you could go about this without a union. Although I think you'd find doing it with a union a little more straight forward.

Thansk for this suggestion! I agree that the union approach is more straight forward 🙂 But good to see other possibilities to solve such an issue.