Cut off unnecessary relationships


Hello! I have graphs consisting of student nodes and classmate relationships (s1)-[:classmate]->(s2).
Is it possible to write a query that cuts off relations between fake classmates? For example, here it is necessary to cut off the Donskoy Ilya.

Depends on which relationships are fake, but deleting relationships is easy, and done like this:

MATCH (:Person { name: "A" })-[rel:classmate]->(:Person { name: "B" })
DELETE rel
RETURN true;

Now all you have to do is adjust the MATCH to catch the fake ones, and it'll be taken care of.

In fact, the task is difficult. Relationships are considered fake when a student is a classmate of only one student from a group of classmates.

something like this might work. Not tested so not sure it is corrrect syntax wise or if you need less then or equal in the where clause

MATCH (a:Person { name: "A" })-[rel:classmate]->(b:Person { name: "B" })
WITH size((b)-[:classmate]->() ) AS others_classmates, 
     size((a)-[:classmate]->() ) AS own_classmates,
WHERE own_classmates < others_classmates
DELETE rel
RETURN true;
3 Likes

I tried:
MATCH (a:student)-[rel:classmate]->(b:student)
WITH size((b)-[:classmate]->() ) AS others_classmates,
size((a)-[:classmate]->() ) AS own_classmates,
WHERE own_classmates < others_classmates
DELETE rel
RETURN true;

Error:
Neo.ClientError.Statement.SyntaxError
Invalid input 'w': expected 'r/R' or 'p/P' (line 4, column 8 (offset: 162))
"WHERE own_classmates < others_classmates"
^

You inserted a comma before your WHERE statement.
If you remove it, it should work.

So it should be like:

MATCH (a:student)-[rel:classmate]->(b:student)
WITH size((b)-[:classmate]->() ) AS others_classmates,
size((a)-[:classmate]->() ) AS own_classmates
WHERE own_classmates < others_classmates
DELETE rel
RETURN true;
1 Like

Yes indeed. Typo on my side. Thanks for noticing @moritzlukasschauer

Hi. I have an error: Variable rel not defined (line 5, column 8 (offset: 196))
"DELETE rel".

Hey,

the variable is defined in the MATCH-clause, but not in the WITH-clause.

So something like

WITH size((b)-[:classmate]->() ) AS others_classmates,
     size((a)-[:classmate]->() ) AS own_classmates,
     rel

should work for you.

1 Like

This code seems to have helped me.

MATCH (a:student)-[rel:classmate]->(b:student)
WITH size((b)-[:classmate]->() ) AS others_classmates,
size((a)-[:classmate]->() ) AS own_classmates, a, b, rel
WHERE others_classmates >= own_classmates
DELETE rel

Be careful using size though. You could get a fake classmate counting as valid if they have the same number of classmates, but not necessarily the exact same classmates.

You would probably want to compare classmate collections for that.

-Mike

1 Like