Maintaining graph structure in returned data

HI all.

I am trying to retrieve data from neo4j in a very particular way. It will help to explain the goal.

The goal is to visualize a web of user discussion. When a user first loads up a discussion on the frontend, I want to retrieve all the posts that are related to it up to a certain depth, that is, all parents and children, recursively, up to a certain depth. Then I need to send to the frontend this data, using some datastructure that would maintain the relationships between nodes. This would really simplify my project since i need to be able to switch between visualizing as a graph and also displaying the discussions in a readable format.

I have already looked at these threads but these looked needlessly complex. I really am trying to do something really quite simple I feel. Cypher: returning custom JSON from a graph projection query - #4 by phil.westwell

Here is the cypher query I have right now that produces the right graph visualization in browser:

MATCH p=()-[:REPLY*1..3]-(post)-[:REPLy|*1..3]-()
        WHERE post.post_id = $head
        RETURN p'

This however, returns individual paths. Will I have to do this "the hard way?" or is there something easier? Am I overthinking it?

Thank you for any help!

Hello @realjosefthorne and welcome to the Neo4j community :slight_smile:

I think the easiest way would be to return a list of distinct nodes and a list of distinct relationships.

MATCH p=()-[:REPLY*1..3]-(post {post_id: $head})-[:REPLY*1..3]-()
WITH apoc.coll.toSet(apoc.coll.flatten(collect(nodes(p)))) AS nodes, 
apoc.coll.toSet(apoc.coll.flatten(collect(relationships(p)))) AS relationships
RETURN nodes, relationships


Thank you! I actually started experimenting doing this with the following cypher code:

MATCH (p:Post {post_id: $head})
        CALL apoc.path.subgraphAll(p, {
        relationshipFilter: "REPLY",
        minLevel: 1,
        maxLevel: $limit,
        beginSequenceAtStartLevel: false
        YIELD nodes, relationships
        RETURN p, nodes, relationships;'

Would your code be better to use here? Advantages and disadvantages? Thanks!

Hello @realjosefthorne :slight_smile:

Your query should be faster than mine and more reliable, good job!