Skip to Content

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 $limit

Offset 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.createdAt alone is not enough: rows with the same timestamp come back in no guaranteed order. When we created 25 posts with one createMany, they shared only 2 or 3 distinct createdAt values. Add p.id as 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 $limit

For 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 / LIMITKeyset (WHERE on last row)
Jump to page nyesno, only next (or previous, comparison reversed)
Stable while rows are inserted or deletednoyes
Can start from an index range seeknoyes, with an index on the sort property
Total page countcount() in a separate querycount() 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:

QueryPlan starts withdb hits
SKIP 4000 LIMIT 10NodeByLabelScan20,001
SKIP 0 LIMIT 10 (first page, for reference)NodeByLabelScan20,001
Keyset, no index on createdAtNodeByLabelScan22,930
Keyset, range index on createdAtNodeIndexSeekByRange9,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}) `;
Last updated on