Include counted node in response of other node

I have a graph like below:

37%20PM

Nodes: (Node {foo: 'foo'}), (Other {bar: 'bar'})

Now, I would like to return response like below:

{
  foo: 'foo',
  total: 2 // count of bar
}
{
  foo: 'foo',
  total: 0 // count of bar
}

But I'm not able to return like so:

MATCH (:Other) - [r:FOR] -> (n:Node)
WITH count(r) as total, n
RETURN n {foo: n.foo, total: total}

It returns only one node:

Something like this ?

MATCH (n:Node)
RETURN n.foo, size((n)-[:FOR]-()) as total

Nicolas's solution is correct, using size() to get the degree of the relationships on the node is quick and easy.

As for the reason you weren't getting any results on the other node in your query, it's because the other node doesn't match your pattern of MATCH (:Other) - [r:FOR] -> (n:Node). Depending on how the planner executed it, it either matched to :Other nodes and expanded out to :Node nodes, or the other way around, and either way it either wouldn't have found the other foo node (if starting from the :Other nodes), or it would have found the lone foo node and filtered it out since it doesn't have any :FOR relationships to traverse.

1 Like

Try this

MATCH (n:Node)
RETURN {foo:n.foo, total:size((n)-[:FOR]-())}
1 Like

Ah, yeah. It works. Thanks.