Neo4jClient - Retrieving relationship from Cypher query

别说谁变了你拦得住时间么 提交于 2019-11-29 16:56:42

You can create a parameterless constructor for your relationship type, you just pass it 'duff' data, which I know sounds bad, but as you don't really need it, it won't hurt you:

public class ActedIn : Relationship<ActedInPayload>, IRelationshipAllowingSourceNode<Actor>, IRelationshipAllowingTargetNode<Movie>
{
    public ActedIn() : base(-1, null) {}
    public ActedIn(NodeReference targetNode, ActedInPayload data) : base(targetNode, data) {}

    public override string RelationshipTypeKey
    {
        get { return "ACTED_IN"; }
    }
}

So this is the ActedIn class, with the parameterless constructor chaining a '-1' down to the base constructor.

Your query then becomes:

var actorsAndRoles = client
    .Cypher
    .Start(new {movie})
    .Match("actor-[r:ACTED_IN]->movie")
    .Return((actor, r) => new
        {
            Actor = actor.As<Node<Actor>>(),
            ActedIn = r.As<RelationshipInstance<ActedInPayload>>()
        })
    .Results;

Note, it's being cast to a RelationshipInstance of type ActedInPayload not ActedIn, then, to get the data you might want:

foreach (var actorsAndRole in actorsAndRoles)
{
    Console.WriteLine("{0} acted as {1} - which is in the db as {2}-[ACTED_IN]->{3}", 
        actorsAndRole.Actor.Data.Name, 
        actorsAndRole.ActedIn.Data.Role, 
        actorsAndRole.ActedIn.StartNodeReference.Id, 
        actorsAndRole.ActedIn.EndNodeReference.Id);
}

Which will give you something like:

Keanu Reeves acted as Neo - which is in the db as 482-[ACTED_IN]->481

Hugo Weaving acted as Agent Smith - which is in the db as 483-[ACTED_IN]->481

Though obviously with different numbers on your own DB.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!