title: Neo4j - return nodes and relationships as a nested object/map
body: <p>I'm trying to essentially get all of the data under a specific high level node and return it as a nested JSON. I've been messing around with it for a while, and I could probably make something work with a lot of OPTIONAL MATCHES and WITH, but it looks gigantic, and it's not clean.</p>
  <p>In addition, I run into issues with duplicates. In the schema below, if x1 has multiple x1 nodes, and multiple y1 child nodes, then I get duplicated x1 nodes in my result set. Which is not ideal.</p>
  <p>Should I just run separate queries, and combine in code? Should I try to go down this path of writing a massive query and try to combine in a single JSON on the fly?</p>
  <p>I'll define my schema first, so I have something like</p>
  <pre><code>(Movie)-[rel1]-(Actor)-[x]
  
  where [x] can be:
  [x1]-(node1)-[y1]
      [y1]-(something)
  
  [x2]-(node2)
      [y1]-(something)
  
  [x3]-(node2)
      [y1]-(something)
  
  [x4]-(node2)
  [x5]-(node2)
  </code></pre>
  <p>and what I want is something like:</p>
  <pre><code>{
  
  Movie: 
     ...movie properties,
     Actor: [
         x1: [
             {
                 ...x1 properties,
                 y1: [
                     {...y1 properties},
                     {...y1 properties}
                 ]
             },
             { another x1 node with properties, and its children of y1's}
         ]
         x2... (like above)
         x3... (like above)
     ]
  
  }
  </code></pre>
  <p>This is the query I've been playing around with. I've tried a few different iterations.</p>
  <pre><code>OPTIONAL MATCH (Movie)-[rel1]-&gt;(Actor)-[x1]-&gt;(node1)-[y1]-(something1)
  WITH Movie, Actor, { node1: COLLECT(node1), something1: COLLECT(something1)} as node1
  
  // continue writing same query as above, with x2 and y2, etc
  
  RETURN {
    Movie: Movie,
    Actor: COLLECT({
      Actor: Actor,
      node1: node1, // this returns duplicates
    })
  }
  
  </code></pre>