如何在neo4j中获取第一邻居的子图



我在neo4j中使用此查询获取节点的第一个n邻居:(在本例中,n=6(

我有一个加权图,所以我也按权重排序结果:

START start_node=node(1859988)
MATCH start_node-[rel]-(neighbor)
RETURN DISTINCT neighbor,
rel.weight AS weight ORDER BY proximity DESC LIMIT 6;

我想获取一个完整的子图,包括第二个邻居(前六个孩子的第一个邻居(。

我试过类似的smtg

START start_node=node(1859988)
MATCH start_node-[rel]-(neighbor)
FOREACH (neighbor | MATCH neighbor-[rel2]-(neighbor2) )
RETURN DISTINCT neighbor1, neighbor2, rel.proximity AS proximity ORDER BY proximity DESC LIMIT 6, rel2.proximity AS proximity ORDER BY proximity DESC LIMIT 6;

语法仍然是错误的,但我也不确定输出:我想要一个由父母、子女和体重组成的元组表:[节点A-节点B-重量]

我想看看它是执行一个查询更好还是执行六个查询更好。有人能帮助澄清如何迭代查询(FOREACH(和格式化输出吗?

谢谢!

好吧,我想我明白了。根据你的评论,这里有另一个尝试:

MATCH (start_node)-[rel]-(neighbor)
WHERE ID(start_node) IN {source_ids}
WITH
  neighbor, rel
ORDER BY rel.proximity
WITH
  collect({neighbor: neighbor, rel: rel})[0..6] AS neighbors_and_rels
UNWIND neighbors_and_rels AS neighbor_and_rel
WITH
  neighbor_and_rel.neighbor AS neighbor,
  neighbor_and_rel.rel AS rel
MATCH neighbor-[rel2]-(neighbor2)
WITH
  neighbor,
  rel,
  neighbor2,
  rel2
ORDER BY rel.proximity
WITH
  neighbor,
  rel,
  collect([neighbor2, rel2])[0..6] AS neighbors_and_rels2
UNWIND neighbors_and_rels2 AS neighbor_and_rel2
RETURN
  neighbor,
  rel,
  neighbor_and_rel2[0] AS neighbor2,
  neighbor_and_rel2[1] AS rel2

它有点长,但希望它至少能给你的想法

首先,您应该避免使用START,因为它(希望(最终会消失。

因此,为了获得一个邻域,你可以使用可变长度的路径来获得远离节点的所有路径

MATCH path=start_node-[rel*1..3]-(neighbor)
WHERE ID(start_node) = 1859988
RETURN path, nodes(path) AS nodes, EXTRACT(rel IN rels(path) | rel.weight) AS weights;

然后,你可以选择路径/节点,并将它们与你选择的语言结合在记忆中。

编辑:

还可以看看这个SO问题:用Neo4j 获取一棵树

它展示了如何将输出作为每个关系的一组开始/结束节点,这在许多情况下可能会更好。

相关内容

  • 没有找到相关文章

最新更新