Search code examples
c#neo4jneo4jclient

How get relationship's startNodeId and endNodeId using Neo4jClient?


var query = client.Cypher
             .Match("(n1)-[r]-[n2]")
             .Where("n1.NodeId={startNodeId} and n2.NodeId={endNodeId}")
             .WithParam("startNodeId",startNodeId)
             .withParam("endNodeId",endNodeId)
             .return((r,n1,n2)=>new {Edge=r.As<Node<string>>(),Type=r.Type()});

By this way,I can only get the relationship's Label and Properties.But I also want to get the relationship's startNodeId and endNodeId. By the way,I can get the relationship's startNodeId and endNodeId by using REST API. How can anyone help me?

Z.Tom


Solution

  • It depends on what you're meaning by startNodeId - if you mean the Neo4j Ids, then you'll be wanting to use the Relationship<T> class:

    client.Cypher
        .Match("(n1)-[r]-(n2)")
        //Your where stuff here.
        .Return(r => r.As<RelationshipInstance<string>());
    

    The T should be a type you've put on the relationship, but if you haven't got that, just use object, you will need to use the Relationship<T> type, you can't use the non-generic version.

    If the startNodeId is a property on a type, then you either do r => r.As<YourType>() or r => r.As<Relationship<YourType>>().

    As a side note, you can use Neo4jClients ability to parse parameters and save some code (also make it more compile safe) with respect to your Where clauses.

    I would write your code as:

    var query = client.Cypher
        .Match("(n1)-[r]-[n2]")
        .Where((NodeType n1) => n1.NodeId == startNodeId)
        .AndWhere((NodeType n2) => n2.NodeId == endNodeId)
        .Return(r => new { Edge = r.As<RelationshipInstance<object>>(), Type = r.Type()});
    

    which auto parses the parameters.