我的数据模型是树形结构,最大深度为3.例如:
(a) ... first level root node
/ | \
/ | \
(b) (b) (b) ... [0..n] number of second depth nodes
/ | |
/ | |
(c) (c) (c) ... [0..n] number of third depth nodes per (b) node
节点之间的关系是:(c)-[:in]->(b)-[:in]->(a)
给定根节点(a),我想创建一个查询,它将返回10个最近(b)节点,以及每个(b)节点上的3个最新(c)节点。
我从这里开始查询以获取10个最近的(b)节点:
match (a) where id(a) = {root_id}
match (a)<-[:in]-(b) where b is not null
return b order by id(b) desc limit 10
这会按预期获得10个最新的b节点。但是,我找不到一种方法来获得每个(b)最近的3个(c)节点。这就是我所拥有的:
match (a) where id(a) = {root_id}
match (a)<-[:in]-(b) where b is not null
with b order by id(b) desc limit 10
optional match (b)<-[:in]-(c)
return b, c order by id(c) desc limit 3;
但是,limit 3
适用于整个回程,而不仅仅是c
子查询。
有没有办法卷起(c)子查询,以便为每个(b)节点应用limit 3
一次?
(我知道节点ID因其波动性而不是最佳使用。我只是使用id()作为本例中订购内容的快捷方式)
答案 0 :(得分:4)
您的查询几乎是正确的,对于前面3个c节点,您可以收集它们并仅返回集合的3个节点:
t = (a[2] << CHAR_BIT) | a[1];
在此测试:http://console.neo4j.org/r/c16wak
Nb:不需要match (a) where id(a) = {root_id}
match (a)<-[:in]-(b) where b is not null
with b order by id(b) desc limit 10
optional match (b)<-[:in]-(c)
with b, c order by id(c)
RETURN b, collect(c)[0..3] as c
,使用MATCH b永远不会为空