Recommended way of getting single relationship of specific type between two nodes

StackOverflow https://stackoverflow.com/questions/21816488

  •  12-10-2022
  •  | 
  •  

Pregunta

Although title is clear,

I need to remove a relationship between two nodes of a specific relationship type. Neither getSingleRelationship function of Node nor overloaded versions of getRelationships have second node parameter.

Should I get all relationships and iterate over it to find relationship? Is there any constant time way?

What is the recommended way in Core API or Traversal API?

¿Fue útil?

Solución 2

Yes you would iterate over the relationships and check the end-node:

public Relationship getRelationshipBetween(Node start, Node end, Direction direction, RelationshipType type) {
    for (Relationship r: start.getRelationships(direction,type)) {
       if (r.getOtherNode(start).equals(end)) return r;
    }
    return null;
}

Otros consejos

Why don't you use a Cypher query? The library has this possibility. Just use the cypher query function (see their doc for the exact name, I don't remember) and then use this query:

START n=node(_id1), m=node(_id2) MATCH n-[rel:RELATIONSHIP_TYPE]-m RETURN DISTINCT rel;

where _id1 and _id2 are the internal ids of the nodes in Neo4J

If you use Neo4J 2.0 (highly recommended), your query would look something like:

MATCH (n{id:"_id1"}), (m{id:"_id2"}), n-[rel:RELATIONSHIP_TYPE]-m RETURN DISTINCT rel;

in that latter case you could actually use any property in the place of id - for example, your own unique id for the node, or their names, etc.

In the end Neo4J is explicitly saying they're moving away from REST API towards Cypher, so it makes sense to use Cypher where possible and it's also more precise what you get like that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top