Pagination in Neo4j: SKIP/LIMIT vs keyset
To paginate in Cypher, sort with ORDER BY on something unique, then use SKIP and LIMIT for
page numbers, or a WHERE on the last row you returned (keyset, or cursor, pagination) for “load
more” and infinite scroll. Always include a unique tie-breaker such as id in the sort, or pages can
repeat and skip rows.
MATCH (p:Post)
WHERE p.published = true
RETURN p.id AS id, p.title AS title
ORDER BY p.createdAt DESC, p.id DESC
SKIP $skip LIMIT $limitOffset pagination: SKIP and LIMIT
For page n of size size, pass $skip = (n - 1) * size and $limit = size. It is the simplest
option and the only one that lets users jump to page 7. Two things to know:
- Order must be total.
ORDER BY p.createdAtalone is not enough: rows with the same timestamp come back in no guaranteed order. When we created 25 posts with onecreateMany, they shared only 2 or 3 distinctcreatedAtvalues. Addp.idas the last sort key. - Pages drift when data changes. If a post is published between page 1 and page 2, everything shifts by one, and the last post of page 1 appears again at the top of page 2. We reproduced exactly that: one duplicate on page 2 after one insert.
SKIP also does not jump ahead: the rows it skips are still read, sorted and thrown away.
From JavaScript, SKIP and LIMIT need integer parameters. A plain JS number is sent as a
float and Neo4j rejects it: “LIMIT: Invalid input. ‘10.0’ is not a valid value. Must be a
non-negative integer.” Pass neo4j.int(10) from neo4j-driver, or convert in the query: SKIP toInteger($skip) LIMIT toInteger($limit).
Keyset pagination: WHERE on the last row
Instead of counting rows to skip, remember the sort keys of the last row you returned and ask for the rows after it:
MATCH (p:Post)
WHERE p.published = true
AND (p.createdAt < $after.createdAt
OR (p.createdAt = $after.createdAt AND p.id < $after.id))
RETURN p.id AS id, p.title AS title, p.createdAt AS createdAt
ORDER BY p.createdAt DESC, p.id DESC
LIMIT $limitFor the first page, drop the $after condition. For the next one, pass the createdAt and id of
the last row as $after. The OR handles ties on createdAt, and the comparison direction (<)
matches the sort (DESC). Walking 25 posts in pages of 10 this way returned all 25 exactly once,
and a post inserted between two pages did not shift the next page.
SKIP / LIMIT | Keyset (WHERE on last row) | |
|---|---|---|
| Jump to page n | yes | no, only next (or previous, comparison reversed) |
| Stable while rows are inserted or deleted | no | yes |
| Can start from an index range seek | no | yes, with an index on the sort property |
| Total page count | count() in a separate query | count() in a separate query |
What PROFILE showed
We profiled both queries on 5,000 published posts (Neo4j 5.26 Community), reading the page after row 4,000:
| Query | Plan starts with | db hits |
|---|---|---|
SKIP 4000 LIMIT 10 | NodeByLabelScan | 20,001 |
SKIP 0 LIMIT 10 (first page, for reference) | NodeByLabelScan | 20,001 |
Keyset, no index on createdAt | NodeByLabelScan | 22,930 |
Keyset, range index on createdAt | NodeIndexSeekByRange | 9,674 |
Two takeaways. Without a usable index, Neo4j reads and sorts every matching post for every page,
whichever style you use, and keyset is not cheaper. With a range index on the sort property (in a
Cyphra schema, createdAt DateTime @index), the keyset query starts from the cursor with an index
seek. Your data and query shape will give different numbers: run PROFILE on your own query.
Paginate with Cyphra
findMany takes orderBy, skip and take, and converts them to integers for you:
import { db } from "./db.js";
const pageSize = 10;
async function postsPage(page: number) {
return db.post.findMany({
where: { published: true },
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
skip: (page - 1) * pageSize,
take: pageSize,
});
}
const total = await db.post.count({ where: { published: true } });
const pages = Math.ceil(total / pageSize);For keyset pagination, select $cursor and pass the last row’s cursor back as cursor.after
(Cursor pagination):
async function postsAfter(after: string | undefined) {
return db.post.findMany({
where: { published: true },
orderBy: [{ createdAt: "desc" }],
take: pageSize,
cursor: { after },
select: { id: true, title: true, $cursor: true },
});
}
let page = await postsAfter(undefined);
while (page.length === pageSize) page = await postsAfter(page[page.length - 1].$cursor);Cyphra appends the @id as the last sort key and compiles the cursor into the WHERE of the Cypher
above (one branch per sort key, ties broken by the next one, null handled where it sorts). The
cursor is an opaque string, ready to hand to a browser, and is rejected with a
CyphraValidationError if it was made for another orderBy. cursor: { before } pages backwards.
The cursor compares the boundary row’s values with = and < / >, which relies on two things for
DateTime keys. Cyphra stores every DateTime at UTC offset Z and sends Date filter values the
same way; this matters because Cypher’s = on two datetimes compares the offset too
(datetime("2024-01-01T00:00Z") = datetime("2023-12-31T19:00-05:00") is false). And a JavaScript
Date has millisecond precision, which is what Cyphra writes; values written by other code with
sub-millisecond precision, or by Cyphra before 0.3 (which used the server’s local offset), will not
compare equal. See DateTime values to normalize them.
Nested relations paginate the same way: include: { posts: { orderBy: { createdAt: "desc" }, take: 5 } }.
In raw Cypher through db.$cypher, values are passed as they are, so use toInteger() for limits:
const take = 5;
const rows = await db.$cypher<{ title: string }>`
MATCH (p:Post) WHERE p.published = true
RETURN p.title AS title
ORDER BY p.createdAt DESC, p.id DESC
LIMIT toInteger(${take})
`;Related
- Typed client: reading
- Count relationships and aggregate
- Parameters and Cypher injection, including integer parameters
- Glossary: Neo4j index