Search code examples
neo4jneo4jclient

Build a dynamic query using neo4j client


I read many questions on this topic and created the following almost dynamic query:

var resQuery = WebApiConfig.GraphClient.Cypher
                .Match("(movie:Movie {title:{title}})")
                .WithParam("title", title)
                .Return(() => new {
                    movie = Return.As<string>("movie.title")
                }).Results;

Unfortunately this isn't dynamic since I'm declaring the movie property in the Return anonymous type.

In all the examples I found the only option is to return the nodes as an object matches the node properties, like: movie = Return.As<string>("movie.title")

I want the Return statement to give me back a key-value pair list of all the node properties (it can be in any representation like JSON etc..), since my nodes are generic and not from a specific object kind every time.

is that possible?


Solution

  • You can do something like this:

    var resQuery = WebApiConfig.GraphClient.Cypher
        .Match("(movie:Movie {title:{title}})")
        .WithParam("title", title)
        .Return(() => Return.As<Node<Dictionary<string,string>>>("movie"));
    
    var results = resQuery.Results.Select(r => r.Data);
    Console.WriteLine(results.First()["title"]);
    

    Alternatively, something like:

    var resQuery = WebApiConfig.GraphClient.Cypher
        .Match("(movie:Movie {title:{title}})")
        .WithParam("title", title)
        .Return(() => Return.As<Node<string>>("movie"));
    
    var results = resQuery.Results;
    List<dynamic> nodes = results.Select(r => JsonConvert.DeserializeObject<dynamic>(r.Data)).ToList();
    Console.WriteLine(nodes[0].title);