Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

neo4j cypher nested collect

Tags:

neo4j

cypher

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?)

like image 909
Bob B Avatar asked Feb 20 '14 01:02

Bob B


People also ask

What Cypher syntax do you use to create a subquery?

CALL {} (subquery)

What is unwind in Neo4j?

With UNWIND , you can transform any list back into individual rows. These lists can be parameters that were passed in, previously collect -ed result or other list expressions. One common usage of unwind is to create distinct lists. Another is to create data from parameter lists that are provided to the query.

How do you perform an aggregation in Cypher?

The Cypher query offers aggregation similar to GROUP BY offered by SQL. The aggregate function can take multiple values and can calculate the aggregated values for them. In this recipe, we will learn the common aggregation techniques, with the help of examples.

How many nodes can a single relationship connect?

A relationship connects two nodes — a start node and an end node. Just like nodes, relationships can have properties.


1 Answers

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)}
like image 195
Sumeet Sharma Avatar answered Oct 16 '22 06:10

Sumeet Sharma