Paging in RavenDB

Paging of a query result is something you normally think about when your application gets really slow. This seldom occurs while developing (you don’t have enough data to feel the pain) therefore the unpleasant surprise wait until your application is in production. And trust me, to add paging as a hotfix while your users can’t work is nothing you want to do.

The “save by default” approach of RavenDB forces you to think about paging early in the development phase. If you ask for an unlimited result set you only will get the first 128 documents. That number is low enough to hit it in development or at last while you test your application. Luckily the implementation for paging is simple and all you need to know is a little bit of LINQ.

Attention: Even when you use paging you will not get more than 1024 results back. If you need to stream data you should look at Query streaming or set based operations for bulk updates/deletes.

This post is part of the RavenDB series. You can find the other parts here:

 

.Net Client

In the .Net client you can simply write a LINQ query that uses .Take() and .Skip() to get the correct results for the paging:

While this fetches the right data you don’t know how many results exist in total. To answer that question you could execute a second query or use the RavenQueryStatistics object like this:

As soon as you know how many results exist you can use that number to build a paging control like this one:

paging on a web page

(The same RavenQueryStatistics can be used to find out if the underlying index for your query is stale or not. All you have to do is check the value of the IsStale property.)

 

HTTP API

If you use the HTTP API you can use paging as well. As explained in Indexes in RavenDB you need to query a specific index. To get the same results back as in the .Net examples (page size of 10, 3. page of books ordered by title) you can use this query:

The pageSize parameter is obvious and does exactly what you expect. The start parameter however needs some explaining. To get the first entry in the index you need to use start = 0 (it uses the zero-based numbering). In the daily use it is simpler to think of start as skip. To get the first entry you skip nothing and to get the 11. entry you skip 10.

 

Next

There is no magic involved to page the results of a query when you’re using RavenDB. In the next post we will see how we can evolve our classes and documents and which details need our attention.

1 thought on “Paging in RavenDB”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.