Search code examples
.netneo4jneo4jclient

How do I use Neo4jClient to get a Neo4j relation by its ID?


I can create a relation and I have its RelationshipReference. But how do I get the rest of the relationship with payload and all?

With a Node I can just client.Get(nodeid) but AFAIK there is nothing similar for relations.


Is Gremlin the way to go? If so - could someone give me a hint as I am still trial-and-horroring on how to do it through Neo4jClient.


Solution

  • You could use an extension method for the IGraphClient itself:

    public static class GraphClientExtensions
    {
        public static RelationshipInstance<T> GetRelationship<T>(this IGraphClient graphClient, RelationshipReference relationshipReference) where T : Relationship, new()
        {
            if(graphClient == null)
                throw new ArgumentNullException("graphClient");
            if(relationshipReference == null)
                throw new ArgumentNullException("relationshipReference");
    
            var rels = graphClient.ExecuteGetAllRelationshipsGremlin<T>(string.Format("g.e({0}).outV.outE", relationshipReference.Id), null);
            return rels.SingleOrDefault(r => r.Reference == relationshipReference);
        }
    }
    

    usage: (IsFriendOf is a Relationship derived class, Data just a POCO)

    var d1 = new Data{Name = "A"};
    var d2 = new Data{Name = "B"};
    
    var d1Ref = graphClient.Create(d1);
    var d2Ref = graphClient.Create(d2);
    var rel = new IsFriendOf(d2Ref) { Direction = RelationshipDirection.Outgoing };
    var relRef = graphClient.CreateRelationship(d1Ref, rel);
    
    //USAGE HERE
    var relBack = graphClient.GetRelationship<IsFriendOf>(relRef);
    

    It's not ideal, but it does make your code a bit easier to read. (Plus you don't need to know the nodes, just the relationship reference)