[Neo] Checking if relationship exists between two nodes

Mattias Persson mattias at neotechnology.com
Sun Apr 25 21:52:16 CEST 2010

As you all (probably) know the Neo4j API has no method
Node#hasRelationshipTo(Node otherNode) and to find out such a thing could
potentially be slow if both the nodes has many relationships (of the
type/direction you want to check).

I just created a utility for that which starts to iterate from the node (of
the two) that the developer thinks/knows has the least relationships. If a
certain amount of relationships have been iterated and not yet found a new
thread is spawned which starts to iterate from the other node in the
opposite direction. The method will return as soon as the first thread finds
a match. I'd guess that's the fastest way currently to do that. The next
level of this would be to add indexing for relationships (which is an
upcoming feature) and go via that instead.

So the code may look like:

(it's in the neo4j-utils component)

  GraphDatabaseUtil graphDbUtil = new GraphDatabaseUtil( graphDb );
  boolean exists = graphDbUtil.relationshipExistsBetween( node1, node2,
      MyRelTypes.MY_TYPE, Direction.OUTGOING );

Mattias Persson, [mattias at neotechnology.com]
Hacker, Neo Technology

More information about the User mailing list