请考虑这个例子:有三个小组和四个人:
CREATE (group1:Group {
name: 'Group 1'
})
CREATE (group2:Group {
name: 'Group 2'
})
CREATE (group3:Group {
name: 'Group 3'
})
CREATE (personA:Person {name: 'Anna'})
CREATE (personB:Person {name: 'Bob'})
CREATE (personC:Person {name: 'Carla'})
CREATE (personD:Person {name: 'Denis'})
CREATE
(personA)-[:IS_PART_OF]->(group1),
(personB)-[:IS_PART_OF]->(group1),
(personB)-[:IS_PART_OF]->(group2),
(personC)-[:IS_PART_OF]->(group2),
(personC)-[:IS_PART_OF]->(group3),
(personD)-[:IS_PART_OF]->(group3)
Anna和Bob属于第1组,Bob和Carla属于第2组,Carla和Denis属于第3组。 一个简单的密码查询将显示这种关系:
MATCH (g:Group)<-[:IS_PART_OF]-(m:Person)
RETURN g, collect(DISTINCT m)
+-------------------------------------------------------------------------+
| g | collect(DISTINCT m) |
+-------------------------------------------------------------------------+
| Node[2]{name:"Group 3"} | [Node[6]{name:"Denis"},Node[5]{name:"Carla"}] |
| Node[1]{name:"Group 2"} | [Node[5]{name:"Carla"},Node[4]{name:"Bob"}] |
| Node[0]{name:"Group 1"} | [Node[4]{name:"Bob"},Node[3]{name:"Anna"}] |
+-------------------------------------------------------------------------+
3 rows
现在,我想展示Anna和Bob所属的所有群组,以及这些群组中的所有成员,包括 Anna和Bob。
我的查询如下:
MATCH (p:Person)-[:IS_PART_OF]->(g:Group)<-[:IS_PART_OF]-(m:Person)
WHERE p.name IN ['Anna', 'Bob']
RETURN g, collect(DISTINCT m)
+----------------------------------------------------------------------+
| g | collect(DISTINCT m) |
+----------------------------------------------------------------------+
| Node[1]{name:"Group 2"} | [Node[5]{name:"Carla"}] |
| Node[0]{name:"Group 1"} | [Node[4]{name:"Bob"},Node[3]{name:"Anna"}] |
+----------------------------------------------------------------------+
2 rows
结果不是我期望的结果。
为什么Bob不作为第2组的成员出现?
答案 0 :(得分:3)
如果图案的关系与左侧和右侧匹配,则图案左侧的节点不会重复。
尝试此查询:
// Find group
MATCH (p:Person)-[:IS_PART_OF]->(g:Group) WHERE p.name IN ['Anna', 'Bob']
// Get all person from group
WITH g
MATCH (g)<-[:IS_PART_OF]-(m:Person)
RETURN g, COLLECT(distinct m)
为了更好地理解,请查看此查询的结果:
MATCH (p:Person)-[:IS_PART_OF]->(g:Group)<-[:IS_PART_OF]-(m:Person)
WHERE p.name IN ['Anna', 'Bob']
RETURN g, p, m
╒═══════════════╤════════════╤═════════════╕
│g │p │m │
╞═══════════════╪════════════╪═════════════╡
│{name: Group 1}│{name: Anna}│{name: Bob} │
├───────────────┼────────────┼─────────────┤
│{name: Group 2}│{name: Bob} │{name: Carla}│
├───────────────┼────────────┼─────────────┤
│{name: Group 1}│{name: Bob} │{name: Anna} │
└───────────────┴────────────┴─────────────┘
当您为g, collect(distinct m)
申请group 1
时,您会收集Bob
和Anna
,而group 2
则会收集Carla
。