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?
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.