2

I would like to count the results of my cypher query by range.

Here's an example : let's say I've a list of books with the year of publication, I'd like to be able to count the number of books matching my cypher query published between 1970 and 1979, 1980 and 1989, ... ,2010 and 2019

armedwing
  • 113
  • 1
  • 10

2 Answers2

3

If you want to do it all in one query I'd do it like this:

MATCH (b:Book)
RETURN SUM(CASE WHEN 1970 <= b.published < 1980 THEN 1 ELSE 0 END) AS `70s`,
       SUM(CASE WHEN 1980 <= b.published < 1990 THEN 1 ELSE 0 END) AS `80s`,
       SUM(CASE WHEN 1990 <= b.published < 2000 THEN 1 ELSE 0 END) AS `90s`,
       SUM(CASE WHEN 2000 <= b.published < 2010 THEN 1 ELSE 0 END) AS `00s`,
       SUM(CASE WHEN 2010 <= b.published < 2020 THEN 1 ELSE 0 END) AS `10s`

Although I don't think this would take advantage of any indexes on b.published. That type of range query only works on Neo4j 2.3 as well.

Nicole White
  • 7,720
  • 29
  • 31
0

If you have a published_year property on Book nodes, then the query would look something like this:

MATCH (b:Book) 
WHERE b.published_year > 1969 AND b.published_year < 1980
WITH count(b) AS num
RETURN num;

A few notes

  1. Be sure the published_year property is an integer - use the Cypher toInt() function when creating the property.
  2. In Neo4j 2.3+ these type of range queries can be supported by an index. Create an index on the published_year property to improve lookup efficiency: CREATE INDEX ON :Book(published_year) More info on indexes here
William Lyon
  • 8,371
  • 1
  • 17
  • 22