How to write neo4j cypher dsl for below query

Viewed 96

I am trying to use neo4j cypher dsl (https://github.com/neo4j-contrib/cypher-dsl) but it is not getting how to add labels in where clause with OR. I want all the nodes who has either label as sportsman or student. Please help me in resovling this.

match (n) where (n:Student) or (n:Sportsman) with n return n.Name
2 Answers

I will convert your cypher query into UNION ALL then do the cypher dsl statement.

This cypher query:

 match (n) where (n:Student) or (n:Sportsman) with n return n.Name

is equivalent to:

 match (n:Student)
 return n.Name
 UNION ALL
 match (n:Sportsman)
 return n.Name

Then below is the cypher dsl:

 var node1 = Cypher.node("Student").named("n")
 var statement1 = Cypher.match(node1)
         .returning(n.property("Name")) 
         .build();

 var node2 = Cypher.node("Sportsman").named("n")
 var statement2 = Cypher.match(node2)
         .returning(n.property("Name")) 
         .build();

 var unionStatement = Cypher.unionAll(statement1, statement2)

 assertThat(cypherRenderer.render(unionStatement))
 .isEqualTo(
    "MATCH (n:`Student`) RETURN n.Name UNION ALL MATCH (n:`Sportsman`) RETURN n.Name");

Here is a working snippet :

var node = Cypher.anyNode().named("n");
var cypher = Cypher.match(node)
           .where(node.hasLabels("Student")).or(node.hasLabels("Sportsman"))
           .returning(node.property("name"))
           .build();

System.out.println(Renderer.getDefaultRenderer().render(cypher));

Result :

MATCH (n) WHERE (n:`Student` OR n:`Sportsman`) RETURN n.name

In general, I would recommend looking at the examples in the cypher-dsl codebase : https://github.com/neo4j-contrib/cypher-dsl/blob/main/neo4j-cypher-dsl-examples/neo4j-cypher-dsl-examples-core/src/test/java/org/neo4j/cypherdsl/examples/core/CypherDSLExamplesTest.java

Related