使用neo4j查找与给定节点具有关系的节点集合的有效方法 [英] Efficient way to find node set having relationships to given nodes using neo4j
问题描述
对于给定的两个节点来说,找到一组共同节点(具有已定义的关系)是否有效?
例如,节点 A1
, B1
, C1
- C4
与关系关系
x
和 y
:
A1 --x - > C1
A1 --x - > C2
A1 --x - > C3
B1 --y - > C2
B1 --y - > C3
B1 --y - > C4
为 A1(x)$ c $设置的公共节点c>和
B1(y)
会是 [C2,C3]
。
在很多情况下,可以利用域的结构来提高性能。假设您知道一般情况下,与<$ c $的数量相比,您的 A
实体具有更少的 x
关系c> y B
个实体之间的关系。然后,您可以遍历A节点的两个步骤,并查看 B
节点出现的位置,并过滤出 C
节点这样。下面是这种方法的一些代码:
Set< Node> found = new HashSet< Node>();
for(关系firstRel:a1.getRelationships(Reltypes.x,Direction.OUTGOING))
{
节点cNode = firstRel.getEndNode();
for(relationship secondRel:cNode.getRelationships(Reltypes.y,Direction.INCOMING))
{
Node bNode = secondRel.getStartNode();
if(bNode.equals(b1))
{
found.add(cNode);
休息;
}
}
}
另一种方法是开始两个线程可以扫描任何一方的关系。第三种方法是创建一个专门的索引来帮助回答这种查询,这显然会影响插入性能。
Is there an efficient way with given two nodes to find a set of their common nodes (with defined relationships).
For example, having nodes A1
, B1
, C1
-C4
connected with relationships x
and y
:
A1 --x--> C1
A1 --x--> C2
A1 --x--> C3
B1 --y--> C2
B1 --y--> C3
B1 --y--> C4
a common node set for A1(x)
and B1(y)
would be [C2, C3]
.
In many cases the structure of the domain can be leveraged to improve performance. Let's say that you know that in general your A
entities have less x
relationships compared to the number of y
relationships on the B
entities. Then you could traverse two steps from the A node and see where the B
node shows up, and filter out the C
nodes this way. Here's some code for this approach:
Set<Node> found = new HashSet<Node>();
for ( Relationship firstRel : a1.getRelationships( Reltypes.x, Direction.OUTGOING ) )
{
Node cNode = firstRel.getEndNode();
for ( Relationship secondRel : cNode.getRelationships( Reltypes.y, Direction.INCOMING ) )
{
Node bNode = secondRel.getStartNode();
if ( bNode.equals( b1 ) )
{
found.add( cNode );
break;
}
}
}
Another way would be to start two threads that scan the relationships from either side.
A third approach would be to create a specialized index that would help answering this kind of queries, which would obviously hurt insert performance.
这篇关于使用neo4j查找与给定节点具有关系的节点集合的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!