For the sake of example, the contrived model I am interested in consists of two entities Books
and Pages
and a relationship PAGE_OF
. I would like to insert new pages and order the PAGE_OF
relationship by assigning a order
property to it in an automated fashion and in one go. I do not want timestamps on the page or otherwise to determine order. So far I have:
MATCH (b:Book {uuid:"8d372e2a-64ca-44ee-b59f-330edb18f3f"})<-[po:PAGE_OF]-(:Page)
WITH po.order AS o, b
ORDER BY po.order DESC
LIMIT 1
WITH head(collect(o)) AS lastOrder, b
CREATE (b)<-[:PAGE_OF {order:lastOrder + 1}]-(p:page {caption: "I am an interesting page"})
RETURN p
This seems to work fine, but I would be interested to hear if this is a decent approach. Is there a better way to do this WITH head(collect(o)) AS lastOrder, b
? Is there a better way in general to order related entities? Are there future issues here with maintenance with this general approach? For example, what if I need to insert a page somewhere? Is the reorder operation messy?
If you are creating Page Node and linking it to a Book Page at a specific interval of time rather than maintaining an order and incrementing it in every insertion of a new page If you store the current datetime in the relationship between Book and Page it would be quite simple right? When you need the page order you can return by order of date in descending order.
So your creation query will be simple as below
MATCH (b:Book {uuid:"8d372e2a-64ca-44ee-b59f-330edb18f3f"})
CREATE (b)<-[:PAGE_OF{createdDate:datetime()}]-(p:page {caption: "I am an interesting page"})
RETURN p
To return the pages in a book your query will be
MATCH (b:Book {uuid:"8d372e2a-64ca-44ee-b59f-330edb18f3f"})<-[r:PAGE_OF]-(p:page) RETURN p ORDER BY r.createdDate DESC