使用Neo4jClient和Cypher从嵌套对象创建图形

时间:2016-08-10 07:47:24

标签: c# .net neo4j cypher neo4jclient

我将一些数据建模为一组简单的嵌套c#对象,我试图使用.Net Neo4jClient从neo4j数据库创建/检索。

我的课程表格如下:

public class Foo {
    public int ID { get; set; }
    public List<Bar> bar { get; set;}
}

public class Bar {
    public int ID { get; set; }
    public List<Baz> baz { get; set;}
}

public class Baz {
    public int ID { get; set; }
}

一旦数据以正确的形式存储在数据库中:

(f:Foo)-[h:HASBAR]->(b:Bar)-[hb:HASBAZ]->(bz:Baz) 

我可以使用以下查询使用collect和optional匹配将数据检索到我的类结构中:

List<Foo> foolist = WebApiConfig.GraphClient.Cypher
    .Match("(f:Foo)-[h:HASBAR]->(b:Bar)")
    .OptionalMatch("(b)-[hb:HASBAZ]->(bz:Baz)")
    .With("f, { ID: b.ID, baz: collect(bz) } as Bar")
    .With("{ ID:f.ID, bar:collect(Bar) } as Foo")
    .Return<Foo>("Foo")
    .Results
    .ToList();

这一切都很完美,数据被正确地序列化为适当的类。

我的问题是我应该如何执行相反的操作?

如同给定一个包含嵌套的多个bar和baz类的Foo类,我可以在一个查询中在数据库中创建上述数据结构吗?

或者我是否必须为每个嵌套级别编写查询?

我知道我可能必须在创建时列出属性,就好像我给客户端一个Foo类,它将创建一个带有“bar”作为属性的节点。

我的问题主要来自第三级嵌套,如果我将第二级(bar)视为一个数组(传入Foo.bar)作为变量,我可以创建多个[:HASBAR]关系。但是在同一个查询中,我还没有找到将正确的Baz节点与Bar节点相关联的方法。

我是否以正确的方式接近这个?

感谢任何回复,提前感谢...

1 个答案:

答案 0 :(得分:2)

嗯, 可以在一个查询中执行 - 很遗憾,由于二级嵌套,我认为你不能使用美味的UNWINDFOREACH,你需要在课堂上做一些时髦的事情,不过,这里有:

首先,我们需要定义类,因此我们可以反序列化属性,但不能序列化它们

public class Foo
{
    public int ID { get; set; }

    [JsonIgnore]
    public List<Bar> bar { get; set; }

    [JsonProperty("bar")]
    private List<Bar> barSetter { set { bar = value;} }
}

public class Bar
{
    public int ID { get; set; }

    [JsonIgnore]
    public List<Baz> baz { get; set; }

    [JsonProperty("baz")]
    private List<Baz> bazSetter { set { baz = value; } }
}

public class Baz
{
    public int ID { get; set; }
}

什么这种疯狂?!?!好吧 - 通过使用[JsonIgnore],我们告诉Json不要序列化或反序列化给定的属性 - 我们要反序列化,这样你的检索查询就可以了 - 所以让private setter与JsonProperty允许我们实现这一目标。

此方法的额外好处是您无需在Cypher生成位中指定要序列化的属性。这就是它的荣耀:

var query = gc.Cypher
    .Create("(f:Foo {fooParam})")
    .WithParam("fooParam", foo);

for (int barIndex = 0; barIndex < foo.bar.Count; barIndex++)
{
    var barIdentifier = $"bar{barIndex}";
    var barParam = $"{barIdentifier}Param";
    query = query
        .With("f")
        .Create($"(f)-[:HASBAR]->({barIdentifier}:Bar {{{barParam}}})")
        .WithParam(barParam, foo.bar[barIndex]);

    for (int bazIndex = 0; bazIndex < foo.bar[barIndex].baz.Count; bazIndex++)
    {
        var bazIdentifier = $"baz{barIndex}{bazIndex}";
        var bazParam = $"{bazIdentifier}Param";
        query = query
            .With($"f, {barIdentifier}")
            .Create($"({barIdentifier})-[:HASBAZ]->({bazIdentifier}:Baz {{{bazParam}}})")
            .WithParam(bazParam, foo.bar[barIndex].baz[bazIndex]);
    }
}

f:Foo位与正常情况一样,后续的for循环允许您定义每个标识符并设置参数。

我不认为这是一个理想的解决方案,但它会起作用,并将在1个查询中执行。 Obvs,这可能会因很多嵌套值而变得笨拙。