Neo4j:对子查询使用“ order by”和“ limit”

dbc*_*bcb 4 neo4j cypher

我有一个数据模型,它是一个树结构,最大深度为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
Run Code Online (Sandbox Code Playgroud)

节点之间的关系是: (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
Run Code Online (Sandbox Code Playgroud)

这将按预期获得最近的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;
Run Code Online (Sandbox Code Playgroud)

但是,不仅limit 3适用于c子查询,还适用于整个返回。

有没有一种方法可以汇总(c)子查询,以便limit 3对每个(b)节点应用一次?

(由于节点易变性,我知道节点ID不是最佳使用。在此示例中,我只是使用id()作为订购商品的快速方法)

Chr*_*sen 5

您的查询几乎是正确的,对于每个b的最后3个c节点,您可以收集它们并仅返回集合的3个节点:

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
Run Code Online (Sandbox Code Playgroud)

在这里测试:http : //console.neo4j.org/r/c16wak

Nb:不需要做where b is not null,通过使用MATCH b永远不会为null