Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
03-15-2020 04:05 AM
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?
Solved! Go to Solution.
03-15-2020 06:41 AM
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.
03-15-2020 06:41 AM
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.
03-18-2020 02:38 AM
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.
All the sessions of the conference are now available online