2
votes

Is there a Cypher query to return a single relationship of each relationship type in a graph?

For example, I have a graph containing 5 relationships typed TYPE_X, 10 relationships typed TYPE_Y, and 1 relationship typed TYPE_Z. The query would return 3 relationships:

()-[r1:TYPE_X]->()
()-[r2:TYPE_Y]->()
()-[r3:TYPE_Z]->()

It doesn't matter which TYPE_X relationship is returned as r1. Ideally, the query wouldn't have to scan every relationship, it would just return a single arbitrary relationship for each type.

This query would be useful for interrogating relationship types and their properties in the interactive browser.


Update based on @christophe-willemsen's answer.

I used the following query:

MATCH ()-[r]->()
RETURN type(r) AS rel_type, collect(r)[0] AS example

to generate the following visualization with one relationship for every type:

rephetio: one relationship per type

2

2 Answers

2
votes

Actually this is pretty easy, you just have to aggregate on the relationship type :

MATCH (a)-[r]->(b)
RETURN type(r), collect(r)[0] AS oneRel

-

REL3    (34)-[20:REL3]->(35)
REL2    (18)-[12:REL2]->(19)
REL1    (6)-[6:REL1]->(7)
0
votes

Selecting one random relationship per type

In Neo4j 3.0.1, I've been using the following command to select a single random relationship per type.

MATCH ()-[r]->()
WITH type(r) AS rel_type, collect(r) AS rels
WITH rel_type, rels, toInt(rand() * size(rels)) AS idx
RETURN rel_type, rels[idx] AS example

The is based on @christophe-willemsen's answer with the addition of random index lookup on the relationship collections.