Stetco Oana
Stetco Oana

Reputation: 125

I want to display the bidirectional relationship between 2 nodes only once

I have a weighted graph, some of the nodes have bidirectional relationships with the same weight. I want to display those nodes in tabular form only once.

MATCH (n1)-[r1:HAS_DESCENDANT]->(n2)-[r2:HAS_DESCENDANT]->(n1) 
RETURN  n1.prefered_name ,r1.weight,r2.weight, n2.prefered_name;

Result of this query, but I want to show me only one row

This code gives me exactly what I need but in doubles.

If I have 2 relationships between 2 nodes (pointing in a different direction) having the same weight I would like to show me only once the specific row. Is this achievable? or because it is bidirectional relationships it has to show me twice?

Upvotes: 1

Views: 160

Answers (2)

cybersam
cybersam

Reputation: 67019

This query is similar to @DaveBennett's, but only filters out a row if both relationships have the same weight:

MATCH (n1)-[r1:HAS_DESCENDANT]->(n2)-[r2:HAS_DESCENDANT]->(n1)
WHERE r1.weight <> r2.weight OR ID(n1) > ID(n2)
RETURN n1.prefered_name, r1.weight, r2.weight, n2.prefered_name;

By the way, it is unintuitive for n1 and n2 to be "descendants" of each other. If this is intentional, you may want to change the name of the relationship type to something less confusing.

Upvotes: 2

Dave Bennett
Dave Bennett

Reputation: 11216

Since the pattern matches both ways you just need to add a WHERE clause to limit the output to only return the match in one direction.

MATCH (n1)-[r1:HAS_DESCENDANT]->(n2)-[r2:HAS_DESCENDANT]->(n1)
WHERE id(n1) > id(n2)
RETURN  n1.prefered_name ,r1.weight,r2.weight, n2.prefered_name;

Upvotes: 2

Related Questions