Neo4j技术问询:已知查询不同边类型语句,如何返回各类型及出现次数?
Get Relationship Types and Their Occurrence Counts in Neo4j
Hey there! Great question—you're already halfway there with your existing query. To get each distinct relationship type along with how many times it appears, you just need to add an aggregation function and let Neo4j handle the grouping for you.
Here's the adjusted query you need:
MATCH (a)-[r]->(b) RETURN type(r) AS relationship_type, COUNT(r) AS occurrence_count ORDER BY occurrence_count DESC
Let me break this down for you:
type(r): This still grabs the name of each relationship type, just like your original query. We alias it asrelationship_typeto make the result set cleaner.COUNT(r): This aggregation function counts every instance of the relationshipr. Since we're pairing this withtype(r), Neo4j automatically groups all relationships by their type before counting—no extraGROUP BYclause is needed (though you could addGROUP BY type(r)if you prefer explicit syntax, it won't change the result).ORDER BY occurrence_count DESC: This is optional, but it's super useful to see the most common relationship types at the top of your results.
For example, if your graph has FOLLOWS and LIKES relationships, your output might look like this:
| relationship_type | occurrence_count |
|---|---|
| FOLLOWS | 150 |
| LIKES | 80 |
If you only want to count distinct relationships (though that's rarely needed here, since each r is a unique relationship instance), you could use COUNT(DISTINCT r) instead—but in most cases, plain COUNT(r) is exactly what you want.
内容的提问来源于stack exchange,提问作者Solomon Bothwell
相关产品推荐
相关产品推荐

