简体   繁体   中英

Cypher: how to navigate graph to find the right path

I'm new to Cypher, I'm trying to learn to navigate a graph correctly. I hava a situation like this: 2 Users have associated the same Service, the service is accessible via an Account. So, the user 'usr01' can access to the Service 'srv01' with account 'acct01'; the user 'usr02 can access to the Service 'srv01' with account 'acct02'. The aim is to extract 2 records like this:

usr01 - srv01 - acct01
usr02 - srv01 - acct02

So, I executed these queries:

  • Creation of nodes:

     create (s:XService {serviceId:'srv01'}) return s; create (u:XUser {userId:'usr01'}) return u; create (u:XUser {userId:'usr02'}) return u; create (u:XAccount {accountId:'acct01'}) return u; create (u:XAccount {accountId:'acct02'}) return u; 
  • Relationship creation:

     MATCH (u:XUser{userId:'usr01'}), (s:XService {serviceId:'srv01'}), (a:XAccount {accountId:'acct01'}) CREATE (u)-[:HAS_SERVICE]->(s)-[:HAS_ACCOUNT]->(a) MATCH (u:XUser{userId:'usr02'}), (s:XService {serviceId:'srv01'}), (a:XAccount {accountId:'acct02'}) CREATE (u)-[:HAS_SERVICE]->(s)-[:HAS_ACCOUNT]->(a) 

The graph result I've received is this

If I execute this query - starting from the user usr01:

MATCH (u:XUser {userId: 'usr01'}) OPTIONAL MATCH (u)-[:HAS_SERVICE]->(s:XService) OPTIONAL MATCH (s)-[:HAS_ACCOUNT]->(a:XAccount) 

RETURN u.userId, s.serviceId, a.accountId;

I obtain this result:

So, how can I do to obtain the result described above (usr01 - srv01 - acct01) and not the cartesian product that I've received? Thanks in advance

The problem is that when you add the relationship between the service and the account you do not indicate an association relationship with the user. As a solution, you can make a smart node "Access Rule":

MERGE (s:XService {serviceId:'srv01'})

MERGE (u1:XUser {userId:'usr01'})
MERGE (ua1:XAccount {accountId:'acct01'})
MERGE (u1)-[:can_access]->(ca1:AccessRule)-[:to_service]->(s)
MERGE (ca1)-[:with_account]->(ua1)

MERGE (u2:XUser {userId:'usr02'})
MERGE (ua2:XAccount {accountId:'acct02'})
MERGE (u2)-[:can_access]->(ca2:AccessRule)-[:to_service]->(s)
MERGE (ca2)-[:with_account]->(ua2)

And a query:

MATCH (u:XUser {userId: 'usr01'})
OPTIONAL MATCH ps = (u)-[:can_access]->(ca1:AccessRule)-[:to_service]->(s:XService)
OPTIONAL MATCH pa = (ca1)-[:with_account]->(a:XAccount)
RETURN u, ps, pa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM