Neo4jClient - 从Cypher查询中检索关系

时间:2013-07-10 15:18:58

标签: relationship cypher neo4jclient

我无法从Cypher查询中检索匹配的关系。

我有这个简单的试用代码:

var movie = client.Create(new Movie { Title = "The Matrix" });

client.Create(new Actor { Name = "Keanu Reeves" },
    new ActedIn(movie, new ActedInPayload { Role = "Neo" }));

client.Create(new Actor { Name = "Hugo Weaving" },
    new ActedIn(movie, new ActedInPayload { Role = "Agent Smith" }));

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

问题是我无法弄清楚如何施放r(具有匹配的关系)。

尝试了各种“.As”类型演员,但都没有奏效。转换为关系不起作用,因为我的关系类没有无参数构造函数 - 但是基本类本身没有无参数构造函数,所以不要认为这会起作用。另一方面,转换为RelationshipReference会导致异常。根本不投射(只返回r)会导致“不支持”的异常。

有关此问题的一些相关SO条目,但建议的代码不再有效或已被弃用。

如何检索匹配的关系?

1 个答案:

答案 0 :(得分:5)

你可以为你的关系类型创建一个无参数的构造函数,你只需传递'duff'数据,我知道听起来很糟糕,但是因为你真的不需要它,它不会伤害了你:

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"; }
    }
}

所以这是ActedIn类,无参数构造函数将'-1'链接到基础构造函数。

您的查询将变为:

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;

请注意,它会被投射到类型为RelationshipInstance 而不是 ActedInPayload的{​​{1}},然后才能获取您可能需要的数据:

ActedIn

这会给你类似的东西:

  

基努·里维斯饰演Neo--在数据库中为482- [ACTED_IN] - >&gt; 481

     

Hugo Weaving担任代理史密斯 - 在数据库中为483- [ACTED_IN] - &gt; 481

虽然你自己的数据库显然有不同的数字。

相关问题