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

How to fetch a subgraph of first neighbors in 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;

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

我试过 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;

语法仍然错误,但我也不确定输出结果: 我想要一个 table 的元组 parent、children 和权重: [node_A - node_B - 体重]

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

谢谢!

首先,您应该避免使用 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 问题:

它展示了如何为每个关系获取一组 start/end 节点的输出,这在许多情况下会更好。

好的,我想我明白了。这是基于您的评论的另一种尝试:

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

有点长,但希望它至少能给你一些启发