How to add a degree property to a node

In a smallish database I try to add to a node a degree property (how many relationships go out from this node).

I tried the following query:

MATCH (p)-[r]->(x) WHERE p.id = "42"
SET p.degree = count(r);

The WHERE clause WHERE p.id = "42" full defines my node, but there seems to be something wrong with the SET clause SET p.degree = count(r), because I get an " Invalid use of aggregating function count(...) in this context " error.

Any idea what's going wrong?

@halloleo
Basically, you cannot put an aggregation function into the SET statement,
you have to separate the 2 things.
So you could do:

MATCH (p)-[r]->(x)
with p, count(r) as degree
set p.degree = degree
return p

Or else, if you can use the APOC Library , you can use the specific function apoc.node.degree:

MATCH (p)-[r]->(x)
set p.degree = apoc.node.degree(p)
return p
2 Likes

Cool. Super thanks @giuseppe_villan .

I certainly will try this - and read the docs on the WITH clause...

BTW, why is there a separate library function in APOC for this? Is it faster than your first, native approach?

@halloleo

I don't think there is that much difference in speed between the two queries.
The advantage of Apoc function is mainly the flexibility, because can be used everywhere (for example in the SET, as in this case) and you can customize the count, filtering it using a relationship pattern. See here for more details.

1 Like