apoc.agg.maxItems

Function APOC Core

apoc.agg.maxItems(item, value, groupLimit: -1) - returns a map {items:[], value:n} where value is the maximum value present, and items are all items with the same value. The number of items can be optionally limited.

Signature

apoc.agg.maxItems(item :: ANY?, value :: ANY?, groupLimit = -1 :: INTEGER?) :: (ANY?)

Input parameters

Name Type Default

item

ANY?

null

value

ANY?

null

groupLimit

INTEGER?

-1

Usage Examples

The examples in this section are based on the following sample graph of people and their dates of birth:

CREATE (:Person {name: "Christopher Nolan", dateOfBirth: date("1970-07-30")});
CREATE (:Person {name: "Tom Cruise", dateOfBirth: date("1962-07-03")});
CREATE (:Person {name: "Nicole Kidman", dateOfBirth: date("1967-06-20")});
CREATE (:Person {name: "Matt Damon", dateOfBirth: date("1970-10-08")});
CREATE (:Person {name: "Jennifer Connelly", dateOfBirth: date("1970-12-12")});

You can collect the people that have the maximal year of birth by running the following query:

MATCH (p:Person)
WITH apoc.agg.maxItems(p, p.dateOfBirth.year) AS maxItems
RETURN maxItems.value AS value, maxItems.items AS items;
Table 1. Results
value items

1970

[(:Person {name: "Christopher Nolan", dateOfBirth: 1970-07-30}), (:Person {name: "Matt Damon", dateOfBirth: 1970-10-08}), (:Person {name: "Jennifer Connelly", dateOfBirth: 1970-12-12})]

You can set the groupLimit (3rd parameter) to set a limit on the number of items returned:

MATCH (p:Person)
WITH apoc.agg.maxItems(p, p.dateOfBirth.year, 2) AS maxItems
RETURN maxItems.value AS value, maxItems.items AS items;
Table 2. Results
value items

1970

[(:Person {name: "Christopher Nolan", dateOfBirth: 1970-07-30}), (:Person {name: "Matt Damon", dateOfBirth: 1970-10-08})]