Search code examples
neo4jclient

dynamically creating a query in Neo4jClient


I am trying to create a dynamic Cypher query with Neo4jClient. My code is turning very redundant because of .Start in Neo4jClient. In .Start, I would like to get nodes from an index. The nodes can be variable from 1 to 10. So I have to create a switch statement, which is getting really long.

               .Start(new
                {
                    n = Node.ByIndexLookup("name_idx", "Name", sNameArray[0]),
                })

For two nodes, it is

               .Start(new
                {
                    n = Node.ByIndexLookup("name_idx", "Name", sNameArray[0]),
                    m = Node.ByIndexLookup("name_idx", "Name", sNameArray[1]),
                })

And so forth

.Match and .With are dynamically generated using string operations, so no issues there. .Return has only limited return value, so no issues there either.

My main concern is because of .Start, I have to repeat the full .Cypher statement. If I can get around it, I will have nice clean code. Any suggestions?


Solution

  • You can use a Dictionary so for example your second version could be:

    .Start(new Dictionary<string, object>{
        {"n", Node.ByIndexLookup("name_idx", "Name", sNameArray[0])},
        {"m", Node.ByIndexLookup("name_idx", "Name", sNameArray[1])},
    }
    

    Which would allow you to do something like:

    var start = new Dictionary<string, object>();
    for(int i = 0; i < sNameArray.Length; i++)
    {
          start.Add("n" + i, Node.ByIndexLookup("name_idx", "Name", sNameArray[i]));
    }
    
    graphClient.Cypher.Start(start).Where( /**** ETC ****/ );