Java – an effective way to use neo4j to find a node set related to a given node
Given two nodes, is there an effective way to find a set of common nodes (with defined relationships)
For example, connect nodes A1, B1, C1-C4 to relationships X and Y:
A1 --x--> C1 A1 --x--> C2 A1 --x--> C3 B1 --y--> C2 B1 --y--> C3 B1 --y--> C4
The common node set for A1 (x) and B1 (y) will be [C2, C3]
Solution
In many cases, the domain structure can be used to improve performance Suppose you know that, in general, your a entity has fewer x relationships than the y-correlation coefficient on B entity Then, you can go through two steps from node a to see where node B displays, and filter out node C in this way Here are some code for this method:
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 method is to start two threads that scan the relationship from both sides
The third method is to create a special index to help answer this query, which will obviously damage the insertion performance