alexanoid
alexanoid

Reputation: 25780

Neo4j Cypher return count and the actual data in the same query for pagination

Is it possible to avoid calling almost the same query twice - one time for count for pagination and then for the actual data, and combine them into the single Cypher call?

Upvotes: 0

Views: 350

Answers (1)

Graphileon
Graphileon

Reputation: 5385

I doing it in a single query was a requirement, you could do something along these lines, assuming you these parameters:

{
  "page": 0,
  "pageSize": 10
}

this query

MATCH (n:Movie) 
WITH COLLECT({title:n.title}) AS allResults
WITH allResults[($page * $pageSize)..($page+1)*$pageSize] AS pageResults,
     toInt(size(allResults)/$pageSize) + 1 AS numPages,
     size(allResults) AS totalCount
RETURN totalCount,$page, numPages, pageResults

returns

╒════════════╤═══════╤══════════╤══════════════════════════════════════════════════════════════════════╕
│"totalCount"│"$page"│"numPages"│"pageResults"                                                         │
╞════════════╪═══════╪══════════╪══════════════════════════════════════════════════════════════════════╡
│46          │0      │5         │[{"title":"Forrest Gump"},{"title":"Appolo 13"},{"title":"The Matrix"}│
│            │       │          │,{"title":"The Matrix Reloaded"},{"title":"The Matrix Revolutions"},{"│
│            │       │          │title":"The Devil's Advocate"},{"title":"A Few Good Men"},{"title":"To│
│            │       │          │p Gun"},{"title":"Jerry Maguire"},{"title":"Stand By Me"}]            │
└────────────┴───────┴──────────┴──────────────────────────────────────────────────────────────────────┘

Upvotes: 3

Related Questions