Neo4j:查找所有节点指向的节点集

时间:2015-04-09 23:02:49

标签: neo4j

更准确地说,假设您有人和动物节点,以及从:likesPerson的{​​{1}}关系。问题是:如何找到人们喜欢的 ALL 所有Animal

示例:

Animal

如果杰克和玛雅是人的宇宙,那么杰克和玛雅都喜欢的动物组只包含狗。

2 个答案:

答案 0 :(得分:1)

使用此示例数据集:

CREATE (jake:Person {name:'Jake'}),
       (maya:Person {name:'Maya'}),
       (dog:Animal {name:'Dog'}),
       (snake:Animal {name:'Snake'}),
       (cat:Animal {name:'Cat'}),
       (jake)-[:LIKES]->(dog),
       (jake)-[:LIKES]->(cat),
       (maya)-[:LIKES]->(dog),
       (maya)-[:LIKES]->(snake)

我认为以下内容很好:

MATCH (p:Person)
MATCH (a:Animal)

WITH a, COLLECT(p) AS people
WHERE ALL(p IN people WHERE (p)-[:LIKES]->(a))
RETURN a.name

http://console.neo4j.org/r/vu3vxp

但它并不像以下那么快:

MATCH (p:Person)
WITH COUNT(p) AS people

MATCH (p:Person)-[:LIKES]->(a:Animal)
WITH a, COUNT(p) AS likes, people
WHERE likes = people
RETURN a.name

http://console.neo4j.org/r/nnrvj2

答案 1 :(得分:1)

所有人喜欢的动物组合(称之为#34; A")必须与单身人喜欢的动物组相同或相同。因此,我们可以通过测试随机人喜欢的动物来加速搜索A.

以下查询计算人数(np),获取一个人喜欢的动物组合(ca),并返回np人喜欢的那组动物(如果有的话)。

MATCH (p:Person)
WITH COUNT(p) AS np

MATCH (p:Person)-[:LIKES]->(a:Animal)
WITH p, COLLECT(a) AS ca, np
LIMIT 1

UNWIND ca AS a
MATCH (x:Person)-[:LIKES]->(a)
WITH a, COUNT(x) AS nx, np
WHERE nx = np
RETURN COLLECT(a) AS result;