EMR
EMR

Reputation: 123

Neo4j cypher query to retrieve data tree

if u want to query for a specific node type and related nodes solution is simple, by using collect function we can achieve this goal like return country, collect(city) as c

but what we should do if we need to retrieve a data tree like bloodline or user->post->comment->like is there any solution to handle this kind of data in cypher output?

Upvotes: 2

Views: 1519

Answers (1)

Kenny Bastani
Kenny Bastani

Reputation: 3308

Given the following graph:

CREATE (user:User { id: 0 })
CREATE (post:Post)
CREATE (comment:Comment)
CREATE (user)-[:POSTED]->(post)<-[:ON]-(comment)<-[:COMMENTED]-(user)
CREATE (user)-[:LIKES]->(comment)

Retrieve the variable length paths using the following query:

MATCH (user:User { id: 0 })
MATCH p=(user)-[*]->(post)
RETURN p
ORDER BY length(p) DESC

Which results in the following output:

+----------------------------------------------------------------+
| p                                                              |
+----------------------------------------------------------------+
| [Node[6]{id:0},:COMMENTED[8] {},Node[8]{},:ON[7] {},Node[7]{}] |
| [Node[6]{id:0},:LIKES[9] {},Node[8]{},:ON[7] {},Node[7]{}]     |
| [Node[6]{id:0},:POSTED[6] {},Node[7]{}]                        |
| [Node[6]{id:0},:COMMENTED[8] {},Node[8]{}]                     |
| [Node[6]{id:0},:LIKES[9] {},Node[8]{}]                         |
+----------------------------------------------------------------+
5 rows
19 ms

To see what is related and how, run the following query:

// What is related, and how
MATCH (a)-[r]->(b)
WHERE labels(a) <> [] AND labels(b) <> []
RETURN DISTINCT head(labels(a)) AS This, type(r) as To, head(labels(b)) AS That
LIMIT 10

Which has the results:

+-------------------------------------+
| This      | To          | That      |
+-------------------------------------+
| "User"    | "POSTED"    | "Post"    |
| "User"    | "COMMENTED" | "Comment" |
| "User"    | "LIKES"     | "Comment" |
| "Comment" | "ON"        | "Post"    |
+-------------------------------------+
4 rows
139 ms

Upvotes: 3

Related Questions