How do I count a node by the number of nodes with a specific property value

I want to figure out the count of nodes with each property. Something like
MATCH (a:car)
RETURN count("big"), count("small")

Hello and welcome to the Neo4j community :slight_smile:

I think you are looking for this


I stand corrected, however I'd wish there was an easier and more intuitive function.

1 Like

There is this way:

MATCH (a:car)
WITH collect(a) AS a
WITH [val IN a WHERE = "big"] AS big, [val IN a WHERE = "small"] AS small
RETURN size(big) AS big, size(small) AS small

If you are using the latest version of Neo4j (4.1), try:

MATCH (a:car)
  WITH a
  WHERE = "big"
  RETURN "big" AS p, count(a) AS c
  WITH a
  WHERE = "small"
  RETURN "small" AS p, count(a) AS c
1 Like, I updated my previous answer with a version that could work on Neo4j 4.1 if you prefer it :slight_smile:

1 Like

Oh this was great. I'm wondering then if I'm able to do other stuff with the listed nodes like I'm now trying to access their properties kind of like

MATCH (a:car)
WITH collect(a) AS a
sum[val.engine_size in a where"big"] as total_big_engine_capacity

Yeah, you can :slight_smile:

Since val is a node (Car), you can get what you want by iterating on it :slight_smile:, you can even create a dictionnary of values if you want to get several properties :slight_smile:

To bypass the collect(a)

You could also write it this way.

MATCH (a:car)
  CASE WHEN ( = 'big') THEN 1 ELSE 0 END as isBig, 
  CASE WHEN ( = 'small') THEN 1 ELSE 0 END as isSmall
RETURN sum(isBig), sum(isSmall)