I am trying to create a Linked List structure with Neo/Cypher as per the recomendation here: CYPHER store order of node relationships of the same label when I create
<
[UPDATED]
In the following queries, for simplicity I pretend that:
Parent
node of interest by name.Foo
.General Notes:
OPTIONAL MATCH
clauses find the sibling, if any, that should follow the child being inserted.FOREACH
clauses take care of linking the that sibling, if any, to the child being inserted, and then deletes the obsolete relationship to that sibling.To unshift the Child
having an id
of 123
right after the Parent
node:
MATCH (p:Parent {name:"Fred"})
OPTIONAL MATCH (p)-[r:Foo]->(c:Child)
WITH p, r, COLLECT(c) AS cs
MERGE (cNew:Child {id:123})
CREATE (p)-[rNew:Foo]->(cNew)
FOREACH (x IN cs |
CREATE (cNew)-[:Foo]->(x)
DELETE r)
RETURN p, rNew, cNew;
To insert the Child
node having an id
of 123
at index 4 (i.e, make it the 5th child):
MATCH (p:Parent {name:"Fred"})
MATCH (p)-[:Foo*3]->()-[r:Foo]->(c:Child)
OPTIONAL MATCH (c)-[r1:Foo]->(c1:Child)
WITH c, r1, COLLECT(c1) AS c1s
MERGE (cNew:Child {id:123})
CREATE (c)-[rNew:Foo]->(cNew)
FOREACH (x IN c1s |
CREATE (cNew)-[:Foo]->(x)
DELETE r1)
RETURN c, rNew, cNew;
To replace the Child
at index 4 (i.e, the 5th child) with the Child
having an id
of 123
:
MATCH (p:Parent { name:"Fred" })
MATCH (p)-[:Foo*4]->(c0)-[r:Foo]->(c:Child)
OPTIONAL MATCH (c)-[r1:Foo]->(c1:Child)
WITH c0, r, c, r1, COLLECT(c1) AS c1s
MERGE (cNew:Child { id:123 })
CREATE (c0)-[rNew:Foo]->(cNew)
DELETE r, c
FOREACH (x IN c1s |
CREATE (cNew)-[:Foo]->(x)
DELETE r1)
RETURN c0, rNew, cNew;
Note: The DELETE r, c
clause always deletes the node being replaced (c
). That is only suitable if that is what you actually want to happen, and will only succeed if c
does not have relationships other than r
. To explore how to address more specific needs, please ask a new question.