Make a linked list using cypher neo4j

436 views Asked by At

Is there any possible way to make a linked list in cypher within one transaction ?
Iv'e tried ForEach with Match but according to neo4jClien it is not possible to set Match in ForEach. My approach :

public static void save(List<Post> nodes)
{
    var gclient = graphdb.getConnection();
    var create1 = gclient.Cypher.Create("(p:Post {nodes})");
    var match = gclient.Cypher.Match("((t)-[r:lastPost]->(last))");
    var create3 = gclient.Cypher.Create("t-[:lastPost]->p, p-[:next]->last");
    var delete = gclient.Cypher.Delete("r");

    string query = create1.Query.QueryText + " " + match.Query.QueryText + " "
                       + create3.Query.QueryText + " " + delete.Query.QueryText;

    gclient.Cypher
           .Match("(t:Tmp)")
           .WithParam("nodes", nodes)
           .ForEach("(newPost in {nodes} | " + query + ")")
           .ExecuteWithoutResults();
}

Thanks in advance .

1

There are 1 answers

5
cechode On BEST ANSWER

this should do the trick.

    static Neo4jClient.Cypher.ICypherFluentQuery addnode<T>(Neo4jClient.Cypher.ICypherFluentQuery q, IList<T> items, int idx, string label)
    {
        string sq = string.Format("({0}:{1} {{{2}}})", "c" + idx, label, "a" + idx);
        q = q.Create(sq).WithParam("a" + idx, items[idx]);
        return q;
    }
    static Neo4jClient.Cypher.ICypherFluentQuery addlink<T>(Neo4jClient.Cypher.ICypherFluentQuery q, int idx1, int idx2)
    {
        string sq = string.Format("{0}-[:LINKEDTO]->{1}", "c" + idx1, "c" + idx2);
        q = q.Create(sq);
        return q;
    }

    public static void Sample<T>(List<T> items, GraphClient client)
    {
        Neo4jClient.Cypher.ICypherFluentQuery q = client.Connection.Cypher;
        for (int i = 1; i < items.Count; i++)
        {
            q = addnode<T>(q, items, i-1, "MYITEM");
            if(i>1)
                q = addlink<T>(q, i-2, i-1);

        }
        q.ExecuteWithoutResults();
    }