Bertjan Broeksema
Bertjan Broeksema

Reputation: 1551

How to get a unique set of node pairs for undirected relationships

I have a simple set of undirected relationships:

(p1)-[r:appears_in_same_doc]-(p2)

I would like to extract id(p1), id(p2) pairs from this. However, when I do the following:

MATCH (p1:person)-[r:appear_in_same_document]-(p2:person)
return id(p1), id(p2)

I get:

id(p1) | id(p2
-------+------
 1     |  2
 2     |  1
 1     |  3
 3     |  1
 etc.

That is, I get for each pair of nodes, both possibilities:

p1, p2 AND p2, p1

in the result set. This is undesired in the application I work on, but I cannot figure out how to get only half of the "possibilities". I.e.

id(p1) | id(p2
-------+------
 1     |  2
 1     |  3
 etc.

Upvotes: 1

Views: 104

Answers (1)

Rik Van Bruggen
Rik Van Bruggen

Reputation: 399

Just do

MATCH (p1:person)-[r:appear_in_same_document]-(p2:person)
where id(p1) > id(p2)
return id(p1), id(p2)

Upvotes: 3

Related Questions