Search code examples
neo4jspring-data-neo4jneo4j-ogm

How can I get Neo4j OGM to wire up all the POJOs returned from a complex query?


Say I have a query like this:

START a=node(1), b=node(2) MATCH p=a-[:LINKED_TO*0..]->b 
WITH nodes(p) as pathList UNWIND pathList AS pathNode 
MATCH breakfast=pathNode-[:HAS_A]->(:Bagel) 
RETURN pathList, breakfast

I want a List<Node> corresponding to pathList, and I want each node in that list to have its Bagel defined. I can get an Iterable<Map<String, Object>> from that query which contains all the information, but the POJOs have null fields where ideally they would reference one another.

Is there any way to get the OGM to spit out fully linked domain objects from a query like this?


Solution

  • Yes, if you use OGM 2.x and you're able to write your query so that it returns the nodes and relationships you want mapped.

    As an example, using a simplified version of your query-

    START a=node(1), b=node(2) 
    MATCH p=a-[:LINKED_TO*0..]->b 
    RETURN nodes(p) as pathList, rels(p) as rels
    

    pathList will give you the List of mapped domain entities. The related entities that are mapped for you will be the ones you returned in rels.

    So essentially, what you return is what is mapped. If you want to map one related entity only, return only that relationship with its end node.

    More examples: https://github.com/neo4j/neo4j-ogm/blob/2.0/core/src/test/java/org/neo4j/ogm/persistence/session/capability/QueryCapabilityTest.java

    If you use OGM 1.x, then entity mapping is not supported if you want a Result or Iterable<Map<String, Object>> back. It will work however if you use session.queryForObject or session.query(Class<T> objectType, String cypher, Map<String, ?> parameters)