gpt4 book ai didi

Neo4j:使用 'order by' 和 'limit' 与子查询

转载 作者:行者123 更新时间:2023-12-05 00:59:35 25 4
gpt4 key购买 nike

我有一个数据模型,它是一个最大深度为 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) 子查询,使得 limit 3对每个 (b) 节点应用一次?

(我知道节点 id 由于其波动性而不是最好使用的。在这个例子中我只是使用 id() 作为一种快速排序的方法)

最佳答案

您的查询几乎是正确的,对于 foreach 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

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

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

关于Neo4j:使用 'order by' 和 'limit' 与子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com