如何限制cypher中的子查询?

时间:2015-03-13 02:04:14

标签: neo4j subquery cypher

假设我的图形数据库中有3个内容,并且这3个内容中的每个都附加了0个或更多个子项。如何进行查询以检索图中每个事物的前2个子项(根据某些任意顺序)。

以下是设置示例:

CREATE (t1:Thing)-[:X]->(a1:SubThing),
             (t1)-[:X]->(a2:SubThing),
             (t1)-[:X]->(a3:SubThing),
             (t1)-[:X]->(a4:SubThing),
       (t2:Thing)-[:X]->(b1:SubThing),
             (t2)-[:X]->(b2:SubThing),
             (t2)-[:X]->(b3:SubThing),
       (t3:Thing);

我可以运行什么匹配命令来接收这样的表:

t           s
(0:Thing)   (3:SubThing)
(0:Thing)   (4:SubThing)
(1:Thing)   (7:SubThing)
(1:Thing)   (8:SubThing)
(2:Thing)   null

这是我正在使用的console.neo4j.org。

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

2 个答案:

答案 0 :(得分:2)

您需要在此处使用OPTIONAL MATCH,由相同的起始节点聚合,并按子元数对结果进行排序:

MATCH (t:Thing)
OPTIONAL MATCH (t)-[:X]->(s)
RETURN t, count(s) AS degree
ORDER BY degree DESC 
LIMIT 2

答案 1 :(得分:1)

这可能是最好的方法。我不能放松收藏,否则我将失去空:Thing

MATCH (t:Thing)
OPTIONAL MATCH (t)-->(s:SubThing)
WITH t, s
ORDER BY id(s)
RETURN t, collect(s)[0..2]
ORDER BY id(t)

然后它返回:

t           collect(s)[0..2]
(0:Thing)   [(3:SubThing), (4:SubThing)]
(1:Thing)   [(7:SubThing), (8:SubThing)]
(2:Thing)   []