I want to get in/out degree of a given node in neo4j. One way is to use the following query:
MATCH (u: Node{ name: 'Node 1' })-[]->(v) RETURN count(v);
This requires looking up for the relations of u
.
Other way is to keep updating the degrees of nodes as and when they are getting inserted and then we can get the degree by just finding the node.
Do we have to maintain this ourselves or neo4j manages it, so that we can get the degrees by just finding the node. I want to do it either through cypher query or in python driver.
Yes, the size()
function is the equivalent of the java getDegree()
method on a node and is O(1) operation :
Return incoming and outgoing :
MATCH (u: Node{ name: 'Node 1' })
RETURN size((u)-->()) AS degreeOut,
size((u)<--()) as degreeIn
This is also equivalent if you want by a specific relationship type :
MATCH (u: Node{ name: 'Node 1' })
RETURN size((u)-[:FOLLOWS]->()) AS followingCount
UPDATE for Neo4j 5 ( size() being deprecated for patterns )
MATCH (u: Node{ name: 'Node 1' })
RETURN COUNT( (u)-->() ) AS degreeOut,
COUNT( (u)<--() ) as degreeIn
MATCH (u: Node{ name: 'Node 1' })
RETURN COUNT( (u)-[:FOLLOWS]->() ) AS followingCount