1 year ago
#387947
Envious
Neo4j - return nodes and relationships as a nested object/map
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]->(Actor)-[x1]->(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
})
}
neo4j
0 Answers
Your Answer