Reputation: 444
I have the following Neo4j graph result.
I
'm using the multiple relationship -[RELATED_TO*]-
command to obtain that.
Match(n:Comment)
MATCH(n)-[RELATED_TO*]-(d:Comment)
return n, d;
I want to display the results in a List where I could say that this answer comes from that answer, or in a JSON cascade file. What is the best approach to reach that?
Upvotes: 2
Views: 2124
Reputation: 16365
I think you can return a JSON cascade structure using the APOC procedure apoc.convert.toTree
. Take a look in this example:
Creating a sample data set:
CREATE (:Comment {id : 1})<-[:RELATED_TO]-(:Comment {id : 2})<-[:RELATED_TO]-(:Comment {id : 3})<-[:RELATED_TO]-(:Comment {id : 4})
Querying:
MATCH p = (n:Comment)<-[RELATED_TO*]-(d:Comment)
// I believe you are interested only in the "complete" path.
// That is: you are not interested in the sub path like (:Comment {id : 2})-[:RELATED_TO]->(:Comment {id : 3}).
// So this WHERE clause is used to avoid these sub paths.
WHERE NOT (n)-->() AND NOT (d)<--()
CALL apoc.convert.toTree([p]) yield value
RETURN value
The output:
{
"_type": "Comment",
"related_to": [
{
"_type": "Comment",
"related_to": [
{
"_type": "Comment",
"related_to": [
{
"_type": "Comment",
"_id": 142701,
"id": 4
}
],
"_id": 142700,
"id": 3
}
],
"_id": 142699,
"id": 2
}
],
"_id": 142698,
"id": 1
}
Alternatively you can return a list of nodes using the nodes() function passing the path as parameter:
MATCH p = (n:Comment)<-[RELATED_TO*]-(d:Comment)
WHERE NOT (n)-->() AND NOT (d)<--()
return nodes(p)
The result will be:
╒═════════════════════════════════════╕
│"nodes(p)" │
╞═════════════════════════════════════╡
│[{"id":1},{"id":2},{"id":3},{"id":4}]│
└─────────────────────────────────────┘
Upvotes: 6