Neo4j技术问询:如何统计路径中各节点的关联关系数?
How to Get
no_of_relationships and Filter Nodes with <1 Relationships in Cypher Hey there! Let's tackle your question step by step. To calculate the number of relationships for each node in your path and filter those with fewer than 1 relationship (i.e., no relationships at all), you can use Cypher's size() function paired with relationship patterns.
Step 1: Calculate Relationship Count for Nodes
The size() function lets you count the number of relationships connected to a node. Here are common variations depending on your needs:
- Total relationships (all types, both directions):
size((node)--()) - Only outgoing relationships:
size((node)-->()) - Only incoming relationships:
size((node)<--()) - Specific relationship type (both directions):
size((node)-[:YOUR_RELATIONSHIP_TYPE]-())
Step 2: Integrate with Your Existing Query
Using your original MATCH clause, we can extend it to calculate the relationship count for each child node, then filter for those with a count less than 1. Here's the full query:
MATCH (parent:Members {id:"1", position:"R"})-[:PARENT_OF]->(child) // Calculate total relationships for each child and alias it as no_of_relationships WITH child, size((child)--()) AS no_of_relationships // Filter nodes with fewer than 1 relationship (zero relationships) WHERE no_of_relationships < 1 // Return the child details and the relationship count RETURN child.id, child.position, no_of_relationships
Notes to Adjust for Your Needs
- If you only care about a specific type of relationship (e.g., only
PARENT_OFconnections), replace(child)--()with(child)-[:PARENT_OF]-()in thesize()function. - Since
no_of_relationships <1is equivalent tono_of_relationships = 0, you can use the latter for more clarity if you're targeting nodes with no relationships at all.
内容的提问来源于stack exchange,提问作者Mesh Manuel
相关产品推荐
相关产品推荐

