Max Yari
Max Yari

Reputation: 3707

Efficiently check if there is at least one relationship of type connected to node, if not - remove node

Let's assume this Neo4j data construct.

(:Store)<-[:FROM]-(:Notification)-[:FOR]->(//users//:User)

Which should serve as, for example, a notification for users on a new sale in a store.
Such a notification may be addressed to a large number of users simultaneously, in this case I can see two approaches for this data modelling:

  1. Create separate :Notification with relationships for each of the :User's; All connected to single :Store node. So when notification is received - relationships and :Notification node is removed.
  2. Approach which i thought should be more effective performance wise and about which my question is: Create a single :Notification node connected to a store and multiple [:FOR]'s for different users. Notification received - :FOR for this user removed, if no :FOR's left - :Notification itself removed .

So my questions are:
Am I correct in assuming that the 2nd one is a better practice?
How can I generally, after deleting a relationship, check if there are more such relationships, and do it without making Neo4j match all connected ones of this type, i.e check if there is at least one relationship of this type left?

Upvotes: 0

Views: 1450

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

Definitely having fewer objects created in the first place would be more efficient in general. It will result in 2n fewer objects (1 node and relationship per user). The exception would be if you had so many users per notification that the node density was too high. To avoid that though you could simply create additional notifications at a particular user threshold.

The following query is adapted from @Luanne's answer to this question which i though was pretty slick.

It presumes that besides the User nodes, the only other connection to the Notification nodes is the store nodes. If the degree of nodes connected to the Notification node is one then it must be just a Store node remaining. Remove the relationship to the Store node and remove then remove the Notification node.

MATCH (n:Notification {name: 'Notification One'} )-[store_rel:FROM]->(s:Store)
WHERE size((n)--())=1
DELETE store_rel, n

Upvotes: 1

Related Questions