neo4jcypherneo4j-java-api

Neo4j cypher return Path with a specific format


I have a cypher query to return the shortest Path between two nodes.

I am using Java JdbcTemplate.

MATCH (nodeA),(nodeB), p = shortestPath((nodeA)-[*..15]-(nodeB)) "  //
                + "WHERE ID(nodeA) = {1} and ID(nodeB) = {2} RETURN nodes(p) as nodes "  //
                + ",relationships(p) as edges

My problem is that I have a Util method that do the mapping of the jdbctempate result. It only works when my cypher returns nodes suchs as :

RETURN { id : id(node), labels : labels(node), data: node } as node

Is there a way to make my initial cypher return the result in that format?


Solution

  • NODES returns a list of nodes, so you can use UNWIND to unpack the list into a set of rows. So in your example...

    MATCH (nodeA),(nodeB), p = shortestPath((nodeA)-[*..15]-(nodeB))
    WHERE ID(nodeA) = {1} AND ID(nodeB) = {2}
    UNWIND nodes(p) as n
    RETURN { id : id(n), labels : labels(n), data: n} as node, relationships(p) as edges
    

    You can use WITH + COLLECT to fold the nodes back into a list, and then perform the same operation on relationships if you need.