15

Imagine a photo album schema w/ Users, Albums, and Photos:

User -[owns]-> Album -[contains]-> Photo

Can I do a nested collect to get Photos nested in Albums, and Albums nested in User? I'd like results similar to:

{ "users": [
    { "name": "roger dodger",
      "albums": [
        { "album": "album1",
          "photos": [
            {"url": "photo1.jpg"},
            {"url": "photo2.jpg"}
          ]
        }
      ]
    }
  ]
}

This seems close but I could not modify it to suit my needs: Nested has_many relationships in cypher (Could the problem be that neo4j 2.0 web console doesn't support the json syntax in that example?)

Community
  • 1
  • 1
Bob B
  • 4,484
  • 3
  • 24
  • 32

1 Answers1

29

Try this query:

MATCH (a:USER)-[:owns]->(b:ALBUM)-[:CONTAINS]->(c:PHOTO)
WITH a,b,{url: c.name} as c_photos
WITH a,{album: b.name , photos: collect(c_photos)} as b_albums
WITH {name: a.name, albums: collect(b_albums)} as a_users
RETURN {users: collect(a_users)}

Edit

To get all properties of a node you can use string representation of the node and then parse it separately using java etc

MATCH (a:User)
WITH {user: str(a)} as users
RETURN {users: collect(users)}
Sumeet Sharma
  • 2,573
  • 1
  • 12
  • 24
  • This is great! 2 questions: 1) Where did you learn about this custom json cypher syntax - can you point me at the documentation? 2) Is there a way to include all properties of a node without assigning json fields to node properties explicitly? – Bob B Feb 21 '14 at 02:20
  • for the first one... i came across such syntax on that same stackoverflow link you shared in the question. Second question: Currently there is no way you can list all properties of a node to iterate over.. But a work around would be to get string representation of the node .. Check my edit.. – Sumeet Sharma Feb 21 '14 at 05:09
  • For collecting all properties of the node you can just collect full node, so changing `...{ album: b.name }` to `{ album: b }` should do the job, you could do the same for others, but personally I would prefer longer query with props that you need to use rather than returning everything (less data returned) – bart Mar 07 '17 at 17:25
  • Lifesaver! I have been doing crazy things before I read this answer. Thanks Sumeet for that, Btw the second part, what is the str() function, I tried it out but seems like the function is removed? – Anil Maharjan Dec 17 '17 at 03:34
  • string representation of the node.. this is quite an old answer it might have got removed/replaced by some other functionality. – Sumeet Sharma Dec 18 '17 at 05:25
  • Is this the same as using `apoc.convert.toTree`? – Redink Nov 18 '21 at 21:09