Reputation: 2038
I am implementing an application that uses the Neo4j graph database.
I have a requirement to implement doubly linked lists in my graph. Doing this in Cypher can be done using large and complex queries. I am thinking that a better way to do this would be to implement the doubly linked list feature via user defined procedures.
Does this make sense?
Upvotes: 1
Views: 228
Reputation: 30397
First, a caution:
In Neo4j, a doubly-linked list won't buy you much. You can already traverse a relationship in the opposite direction, so if this is purely for traversal, it's not needed at all, and you shouldn't see performance improvement from it unless special cases are in play in your data model.
If you do need to know how to create a doubly-linked list, then see below:
You'll probably want APOC Procedures for this, apoc.nodes.link() in the Creating Data section is a procedure that takes in a collection of nodes and allows you to create relationships between each of the nodes in a linked-list style.
Unfortunately APOC doesn't have a function to reverse the list so you can run apoc.nodes.link() again, so you'll have to follow-up either with a query for the same nodes but in reverse order, or a query to match on any two nodes that are linked and merge in the second relationship.
An example on the Movies graph:
MATCH (m:Movie)
WITH m
ORDER BY m.released ASC
WITH COLLECT(m) as movies
CALL apoc.nodes.link(movies, 'Next')
MATCH (m:Movie)-[:Next]->(n:Movie)
MERGE (n)-[:Prev]->(m)
Upvotes: 1