简体   繁体   English

Neo4j,Cypher:仅匹配包含特定“用户”的“组”

[英]Neo4j, Cypher: Match the “group” comprising specific “users” only

I have (:User) nodes which are grouped [:IN] (:Group) nodes. 我有(:User)节点,这些节点被分组为[:IN] (:Group)节点。

CREATE (u1:User {name: 'u1'}), (u2:User {name: 'u2'}), (u3:User {name: 'u3'})
CREATE (g1:Group {name: 'g1'}), (g2:Group {name: 'g2'})
CREATE u1-[:IN]->g1, u2-[:IN]->g1, u3-[:IN]->g1
CREATE u1-[:IN]->g2, u2-[:IN]->g2
RETURN *

Given "u1" and "u2" I want to find out which (:Group) they ALONE belong to, ie "g2." 给定“ u1”“ u2”,我想找出它们单独属于哪个(:Group) ,即“ g2”。 My first attempt is INCORRECT : 我第一次尝试是不正确的

MATCH (u:User)
WHERE u.name IN ['u1', 'u2']
WITH u
MATCH (u)-[:IN]->(g:Group)
RETURN g, collect(u)

It understandably returns the two (:Group) 's these users belong to. 它可以理解地返回这些用户所属的两个(:Group)

How would find out that "u1" and "u2" alone belong to "g2?" 如何找出“ u1”“ u2”单独属于“ g2”?

You can try a criterion like "both 'u1' and 'u2' are members of the group and there are only two members of the group". 您可以尝试使用“ u1和u2都是该组的成员,而该组只有两个成员”这样的条件。 Here's one way to say that in cypher 这是用密码说的一种方法

MATCH (:User { name:'u1' })-[:IN]->(g)<-[:IN]-({ name:'u2' })
MATCH g<-[:IN]-(m)
WITH g, collect(m) AS members
WHERE length(members)= 2
RETURN *
MATCH (g:Group)<--(m:User)
WITH g, collect(m) AS m
WHERE length(m) = 2 AND ALL (u IN m WHERE u.name IN ['u1','u2'])
RETURN *

to make sure that the group not only contains 2 users but those users are u1 and u2 确保该组不仅包含2个用户,而且这些用户是u1和u2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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