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(a.property="big"), count(a.property="small")

Hello @alec.wang and welcome to the Neo4j community :slight_smile:

I think you are looking for this

Regards,
Cobra

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

There is this way:

MATCH (a:car)
WITH collect(a) AS a
WITH [val IN a WHERE val.property = "big"] AS big, [val IN a WHERE val.property = "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)
CALL {
  WITH a
  WHERE a.property = "big"
  RETURN "big" AS p, count(a) AS c
  UNION ALL
  WITH a
  WHERE a.property = "small"
  RETURN "small" AS p, count(a) AS c
}
RETURN p, c

@alec.wang, I updated my previous answer with a version that could work on Neo4j 4.1 if you prefer it :slight_smile:

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 val.property="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)
WITH 
  CASE WHEN (a.property = 'big') THEN 1 ELSE 0 END as isBig, 
  CASE WHEN (a.property = 'small') THEN 1 ELSE 0 END as isSmall
RETURN sum(isBig), sum(isSmall)