使用 Cypher 从 Neo4j 图中提取子图 [英] Extract subgraph from Neo4j graph with Cypher

查看:42
本文介绍了使用 Cypher 从 Neo4j 图中提取子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Neo4j 中有 5 个节点的集合,这样集合中的每个节点都至少连接到集合中的另一个节点.我想从 Neo4j 中提取由节点集合及其交互形成的子图.目前,我正在使用一种非常原始的方法,该方法涉及尝试从系统中的每个节点到每个其他节点查找匹配项:

Suppose I have a collection of 5 nodes in Neo4j, such that each node in the collection is connected to at least one other node in the collection. I want to extract the subgraph formed by the collection of nodes and their interactions from Neo4j. Currently, I'm using a really primitive method that involves attempting to find a match from each node in the system to every other node:

MATCH p=(n)-[]->(m)
WHERE id(n) IN [3,4,5,6,7] AND id(m) IN [3,4,5,6,7]
RETURN relationships(p);

然而,这个查询既冗余又低效;它必须遍历集合中节点的每个排列(例如,它将匹配节点 #3 和 #4,以及 #4 和 #3).是否有任何更有效的方法可以仅使用 Cypher(非 Java)来获取由这些节点形成的子图?

However, this query is both redundant and inefficient; it must go through every permutation of nodes in the collection (e.g. it will match node #3 and #4, and ALSO #4 and #3). Is there any more efficient way of getting the subgraph formed by these nodes using Cypher ONLY (no Java)?

这是我所说的子图"的一个例子:

Here's an example of what I mean by "subgraph":

我希望 Cypher 返回所有标记为绿色的关系.请注意,集合中的节点不必与图形的其余部分隔离;它们仍然可以与图中的其他节点有关系,但我希望 Cypher 只返回绿色的关系.

I want Cypher to return all the relationships marked in green. Please note that the nodes in the collection don't have to be isolated from the rest of the graph; they can still have relationships with other nodes in the graph, but I want Cypher to return only the relationships in green.

推荐答案

我想扩展理查兹的答案,您也可以将其限制为 id 在不同组中的节点.

I want to extend on Richards answer, you can also restrict it to nodes whose id's are in separate groups.

MATCH (n) WHERE id(n) IN [3,4,5,6,7]
MATCH p=(n)-->(m) 
WHERE id(n) < id(m) AND id(m) IN [3,4,5,6,7]
RETURN relationships(p);

结果

这篇关于使用 Cypher 从 Neo4j 图中提取子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆