13

How should I check if two nodes have relationship with each other,in neo4j embedded database in java?

I want the syntax please or a tutorial link,I have seen neo4j website but didn't find it.

Thanks.

fereshteh
  • 499
  • 5
  • 18

2 Answers2

12

Given two nodes "nodeA" and "nodeB",

  1. gets all relationships attached to "nodeA",

    rels = nodeA.getRelationships();
    
  2. iterate through the collection of relationships "rels", for each relationship "rel", test whether the other end node is nodeB

    rel.getOtherNode(nodeA).equals(nodeB)
    
  3. if the above expression holds true for one of the relationships, then nodeA and nodeB are connected.

Here is the java API for "Node" and "Relationshiip",

http://api.neo4j.org/current/

Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
Lisa Li
  • 2,562
  • 15
  • 11
  • 2
    I just thought I would add, that you should consider the edge counts of `nodeA` and `nodeB` before performing this search, as you can perform it starting from either node. – Matt Way Sep 07 '14 at 02:21
  • 2
    This does not work well if you potentially have many thousands of relationships. – davedonohue Mar 09 '16 at 20:32
0
private boolean sharedRelationshipExists( Node nodeA, long nodeBId)
{
    Iterator<Relationship> iterator = nodeA.getRelationships().iterator();
    while ( iterator.hasNext() )
    {
        if (iterator.next().getOtherNode( nodeA ).getId() == nodeBId) return true;
    }
    return false;
}

// in another part
boolean sharedRelationshipBetweenAB;
if ( nodeA.getDegree() < nodeB.getDegree() )
{
    sharedRelationshipBetweenAB = sharedRelationshipExists( nodeA, nodeB.getId() );
}
else
{
    sharedRelationshipBetweenAB = sharedRelationshipExists( nodeB, nodeA.getId() );
}

the boolean sharedRelationshipBetweenAB will hold your answer

manonthemat
  • 6,101
  • 1
  • 24
  • 49