Adjust relation based on condition

Hello neo4j community,

im new to neo4j and i struggle a lot with this query.

I have 100 "seat" and 50 "day" nodes. For every day a random amount of "seat" have the relation "AVAILABILITY" to exactly 1 "day". For example day 23 has 33 "AVAILABILITY" relations to different "seat" nodes.

(:seat)-[:AVAILABILITY]->(:day)

A day can have "RESERVATION" relation to "seat" if a "AVAILABILITY" exist.

(:seat)<-[:RESERVATION]-(:day)

Now i want to adjust the amount of "AVAILABILITY" for every day to 30 but it should ignore every day that have more then 30 "RESERVATION". Also the deletion of "AVAILABILITY" (adjust to 30) should not delete "AVAILABILITY" for a seat that has already a "RESERVATION".

Thanks for help!

Okay, so the approach here is to first MATCH to all :day nodes that have less than 30 :RESERVATION relationships.

Next per :day node you can MATCH out :RESERVATION relationships to :seat nodes and collect those, this will be our list of seats to exclude from the next match.

Next MATCH out :AVAILABILITY relationships to :seat nodes that aren't in the excluded list, and collect the relationships. You can take the slice of any beyond 30, since that's the segment we want to delete. (If you want this to be random you can use APOC Procedures for this to shuffle the list before taking the segment beyond 30).

Then we delete all relationships in that list. The remaining relationships will be cut to 30.

We can use pattern comprehension to do the equivalent of MATCHing and collecting.

Here's the query:

MATCH (d:day)
WHERE size((d)-[:RESERVATION]->()) < 30 AND size((d)<-[:AVAILABILITY]-()) > 30
WITH d, [(d)-[:RESERVATION]->(seat) | seat] as takenSeats
WITH d, [(d)<-[r:AVAILABILITY]-(seat) WHERE NOT seat IN takenSeats | r][30..] as toDelete
FOREACH (rel in toDelete | DELETE rel)
2 Likes

Thanks helped me a lot :slight_smile: