Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

Order neo4j cypher query by node depth

I have the following graph:

graph

I want to return all users which have the CAN_DISTRIBUTE Credits permission attached through a Role which APPLIES_ON a Group.

The following query returns both sara and admin as user names:

MATCH (users)-[:IS]->()<-[:CHILD_OF*0..]-(roles)-[:CAN_DISTRIBUTE]->(asset:Asset{name:"Credits"}), (roles)-[:APPLIES_ON]->(group:Group{name:"Digital"}) WITH DISTINCT users RETURN collect(users.name)

Now, I'm having a really hard time to order the users returned by their Role relationship depth. I want sara to be returned first as the Manager role is a child of SuperManager. In english it's like saying, give me all the users which can distribute credits on group X, ordered by their role hierarchy.

Do you guys have any ideas?

Here is the query to create this graph:

CREATE (admin:User{name:"admin"}) CREATE (sara:User{name:"sara"}) CREATE (c:Asset{name:"Credits"}) CREATE (marketing:Group{name:"Marketing"}) CREATE (digital:Group{name:"Digital"}) CREATE (super_manager:Role{name:"SuperManager"}) CREATE (manager:Role{name:"Manager"}) CREATE (manager)-[:CAN_DISTRIBUTE]->(c) CREATE (admin)-[:IS]->(super_manager) CREATE (sara)-[:IS]->(manager) CREATE (super_manager)-[:APPLIES_ON]->(marketing) CREATE (super_manager)-[:APPLIES_ON]->(digital) CREATE (manager)-[:APPLIES_ON]->(marketing) CREATE (manager)-[:APPLIES_ON]->(digital) CREATE (manager)-[:CHILD_OF]->(super_manager)

Upvotes: 3

Views: 678

Answers (1)

Bruno Peres
Bruno Peres

Reputation: 16373

You can do it using the length of the entire path, this way:

MATCH p = (users)-[:IS]->()<-[:CHILD_OF*0..]-(roles)-[:CAN_DISTRIBUTE]->(asset:Asset{name:"Credits"}),
      (roles)-[:APPLIES_ON]->(group:Group{name:"Digital"})
WITH DISTINCT users, length(p) as pathLength
RETURN users.name
ORDER BY pathLength

The output for the given data set:

╒════════════╕
│"users.name"│
╞════════════╡
│"sara"      │
├────────────┤
│"admin"     │
└────────────┘

Upvotes: 2

Related Questions