如何有效地构造形式的查询:
匹配(a)-[:Foo]->(b)在(a)-[:Bar]->(c)AND(a)-[:Bar]->(d)中返回a
这是对
[Foo]----(b)
(a)---|
[Bar]----(c)
|
[Bar]----(d)
Run Code Online (Sandbox Code Playgroud)
但是,我希望具有关系Bar的可变数量的目标节点(不仅是c和d,还包括任何节点列表)。
换句话说,如果与[c,d,...]节点列表具有Bar关系,则返回'a'
当前,我手动将WHERE子句连接在最上面,但是我觉得有一种更性感的方式可以做到这一点。
是的,有一种更性感的方法。请参阅http://console.neo4j.org/r/8zx2l2,以在Neo4j控制台中进行最小化设置。我使用了以下密码查询:
MATCH (a:A)-[:Foo]->(b)
WITH a
MATCH (a)-[:Bar]->(other)
WITH a, count(other) AS count
WHERE count=2
RETURN a
Run Code Online (Sandbox Code Playgroud)
该WHERE条件检查路径数是否等于您的要求(此处假设2)。因此,您只需要在一个地方检查。那足够性感;-)?
如果要确保other节点在目标节点的给定列表中:
MATCH (a:A)-[:Foo]->(b)
WITH a
MATCH (a)-[:Bar]->(other)
WITH a, count(other) AS count, collect(other) as others
WHERE all(x in [c,d,....] WHERE x in others)
RETURN a
Run Code Online (Sandbox Code Playgroud)
这样可以确保与数组中列出的所有节点a都有Bar关系[c,d,...]。