Search code examples
neo4jclient

Neo4jClient - How to check if property exists


I'm having trouble converting the following Cypher query to the Neo4jClient syntax.

MATCH n WHERE NOT (HAS (n.User)) OR n.User = "username" RETURN n

This is what I currently have with the addition of some relationship logic and the omission of the HAS logic

var results = Client.Cypher
               .OptionalMatch("(result)-[connection:Connection]-(result2)")
               .Where((Result result) => result.User == username)
               .Return((result, connection, result2) => new Neo4jResultSingle()
               {
                   SearchedNode = result.As<Node<Result>>(),
                   RelationshipConnection = connection.As<RelationshipInstance<Connection>>(),
                   Relationship = connection.As<RelationshipInstance<ConnectionRelationship>>(),
                   RelationshipedNode = result2.As<Node<Result>>()
               }).Results.ToList();

Solution

  • Looking at a combination of your original query and your C# maybe the following might help?

    var results = Client.Cypher
               .Match("(result)-[connection:Connection]-(result2)")
               .Where("WHERE NOT HAS(n.User) OR n.User = {username}")
               .WithParams(new { username = username })
               .Return((result, connection, result2) => new Neo4jResultSingle()
               {
                   SearchedNode = result.As<Node<Result>>(),
                   RelationshipConnection = connection.As<RelationshipInstance<Connection>>(),
                   Relationship = connection.As<RelationshipInstance<ConnectionRelationship>>(),
                   RelationshipedNode = result2.As<Node<Result>>()
               })
               .Results
               .ToList();
    

    This rewrites your WHERE clause to include both the HAS and username logic, whilst parameterising it to cache the query plan and protect against injection.