Cypher query: Get a count grouped by relationship property

社会主义新天地 提交于 2019-12-11 14:10:11

问题


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:

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:


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;


来源:https://stackoverflow.com/questions/48175385/cypher-query-get-a-count-grouped-by-relationship-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!