Title: Neo4j - return nodes and relationships as a nested object/map
Tags: neo4j
Question: 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.
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.
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?
I'll define my schema first, so I have something like
(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)
and what I want is something like:
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)
This is the query I've been playing around with. I've tried a few different iterations.
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
Comment: I think it will be clearer if you will provide sample data, similar to the edit [here](https://stackoverflow.com/questions/71777839/neo4j-how-to-sum-up-relationship-values-over-different-hop-distances) for example.

Comment: Probably you only need to add distinct to the collect function

Comment: You should be able to do it with pattern comprehension. Something like this:
https://www.markhneedham.com/blog/2019/08/22/neo4j-cypher-nested-pattern-comprehensions/



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:04/07/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<neo4j>', 'Title': 'Neo4j - return nodes and relationships as a nested object/map', 'ViewCount': 99, 'id': 71784840, 'user_AboutMe': '', 'user_AccountId': 1346322.0, 'user_DisplayName': 'Envious', 'user_Reputation': 478.0, 'user_Views': 63.0, 'user_id': 1286996.0}}