Spring Data Neo4j custom query that maps node entity inside COLLECT aggregate

94 Views Asked by At

I'm having an issue when trying to map a node entity inside a COLLECT aggregate.

For example, consider that a Company has zero or more Employees. In a graph database, I can create the following relationship between two nodes:

MATCH (e:Employee { name:'Michael' }), (c:Company { name:'Acme'})
CREATE (e)-[r:WORKS_FOR {hired: datetime()}]->(c);

For whatever reason, I now want to write a custom query to fetch all employees in a company.

NOTE: I understand I can annotate the relationship in the MyCompany entity, but I want to do it in a custom query.

For example:

@Query(value=
  """
  MATCH (c:Company {name:$name})<-[r:WORKS_FOR]-(e:Employee)
  RETURN c AS company, COLLECT({employee:e, type:type(r)}) as relationships;
  """)
MyResult findRelationships(String name);

The POJOs are (excluding most of the annotations intentionally):

@Node("Company")
class MyCompany {
  private String name;
}

@Node("Employee")
class MyEmployee {
  private String name;
}

class MyRelationship {
  private MyEmployee employee;
  private String type;
}

class MyResult {
  private MyCompany company;
  private Set<MyRelationship> relationships;
}

This query works perfectly fine using the Cypher Shell CLI. Furthermore, if I avoid the COLLECT and simply return the company, employee and the relationship type, Spring Data works as expected (other than returning multiple matching rows for each permutation).

However, when running in the application using Spring Data with the COLLECT, I get the following error:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed:
  org.springframework.data.mapping.MappingException:
  Error mapping {type: "WORKS_FOR", employee: node<58>}] with root cause
  java.util.NoSuchElementException: No value present

I think they call this a projection?

Some database/app details:

Database: "Neo4j Kernel" | "5.8.0" | "community"
App (spring-boot-starter-parent): 3.1.0
App (org.neo4j:neo4j-cypher-dsl:jar:2023.2.0:compile)
App (org.neo4j.driver:neo4j-java-driver:jar:5.8.0:compile)
App (org.projectlombok:lombok:jar:1.18.28:provided)
App (JDK 17.0.2)
App (Cypher-DSL Dialect.NEO4J_5)

Any help would be greatly appreciated!

0

There are 0 best solutions below