You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 as relationship_type to make the result set cleaner.
  • COUNT(r): This aggregation function counts every instance of the relationship r. Since we're pairing this with type(r), Neo4j automatically groups all relationships by their type before counting—no extra GROUP BY clause is needed (though you could add GROUP 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_typeoccurrence_count
FOLLOWS150
LIKES80

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:54:57