2016-05-29 81 views
0

請考慮下面的例子:有三組和四個人:的Neo4j從收集功能缺失節點

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) 

安娜和Bob屬於組1,Bob和卡拉是第2組和Carla和丹尼斯的成員在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 

現在,我要展現給其安娜和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組的成員?

回答

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你收集BobAnnagroup 2你收集Carla

+0

很好的解釋! – schabluk