0
votes

I am new to Neo4j/Cypher and I am having some trouble grouping by relationship properties.

Firstly a toy example:

CREATE (A1:Worker {ref:"A1"})
CREATE (A2:Worker {ref:"A2"})

CREATE (B1:Worker {ref:"B1"})
CREATE (B2:Worker {ref:"B2"})

CREATE (A1)-[:StreamsTo {type:"stream1"}]->(B1)
CREATE (A1)-[:StreamsTo {type:"stream2"}]->(B1)
CREATE (A1)-[:StreamsTo {type:"stream1"}]->(B2)
CREATE (A1)-[:StreamsTo {type:"stream2"}]->(B2)

CREATE (A2)-[:StreamsTo {type:"stream1"}]->(B1)
CREATE (A2)-[:StreamsTo {type:"stream1"}]->(B2)

This creates a graph with 4 worker nodes, where the A nodes are connected to the B nodes by relationships that can have different values for the "type" property. In this case A1 is connected to the B's by 2 different types of streams and A2 only by 1 type:

sample graph

What I want to be able to do is to count the number of outgoing relationships from each source node but have them grouped by the various values of the "type" property in the relationship to get something like this:

+--------+-------------+---------------+
| Worker | StreamType  | OutgoingCount |
+--------+-------------+---------------+
| A1     | stream1     | 2             |
+--------+-------------+---------------+
| A1     | stream2     | 2             |
+--------+-------------+---------------+
| A2     | stream1     | 2             |
+--------+-------------+---------------+

So far I can get the total outgoing and number of distinct outgoing types:

MATCH (source:Worker)-[st:StreamsTo]->(:Worker)
RETURN source.ref as Source, 
       COUNT(st) as TotalOutgoing, 
       COUNT(distinct st.type) as NumberOfTypes;

Any hints would be helpful.

1

1 Answers

2
votes

So it turns out to be trivial! I had not understood that what you return along with the COUNT() function performs the group by:

MATCH (source:Worker)-[st:StreamsTo]->(:Worker) 
RETURN source.ref as Worker, 
       st.type as StreamType, 
       COUNT(st) as OutgoingCount;