OPTIONAL MATCH不为断开连接节点返回路径

时间:2017-12-10 11:10:50

标签: neo4j cypher

我觉得奇怪的是,使用没有预期关系的OPTIONAL MATCH节点不会作为路径中的单个节点返回。

OPTIONAL MATCH path = (:Person) -[:LIKES]- (:Movie) 
UNWIND nodes(p) as n 
UNWIND rels(p) as e 
WITH n 
WHERE HEAD(LABELS(n)) = “Person” 
return COUNT(DISTINCT n)

退回的人数仅包括喜欢看电影的人。通过使用OPTIONAL我会期望所有人都被退回。 有没有解决方法,或者我在查询中做错了什么?

1 个答案:

答案 0 :(得分:1)

更好的方法是匹配所有:人口节点,然后使用OPTIONAL MATCH匹配电影(或者,如果你想要他们喜欢的电影集合,请使用pattern comprehension )。

如果确实需要在空集合上执行UNWIND而不擦除行,请在某些条件下使用CASE来使用单元素列表而不是空列表。

MATCH (n:Person)   // match all persons
OPTIONAL MATCH p = (n) -[:LIKES]- (m:Movie) // p and m are the optionals
UNWIND CASE WHEN p is null THEN [null] ELSE nodes(p) END as nodes  // already have n, using a different variable
UNWIND CASE WHEN p is null THEN [null] ELSE rels(p) END as e // forcing a single element list means UNWIND won't wipe out the row
WITH n 
WHERE HEAD(LABELS(n)) = “Person”  // not really needed at all, and bad practice, you don't know the order of the labels on a node
return COUNT(DISTINCT n) // if this is really all you need, just keep the first match and the return of the query (without distinct), don't need anything else
相关问题