This blog post is part of the ongoing series “OData FAQ’s”
Today we will look at the system query definitions for $top, $skip to do pagination and $count/$inlinecount to get a count of the number of records in the record set.
How do restrict the amount of data returned?
This is done by calculating an offset and the number of records to return. The offset is set using the $skip system query option and the number of items returned via the $top system query option. If only the first n items are required then it is sufficient to omit the $skip directive.
http://odata.netflix.com/v2/Catalog/Titles?$top=5 will return the top 5 items from the titles catalog at netflix. Here are using an implicit $skip of 0 and a $top of 5.
Compare this with the following which returns the titles from 1-6 in the netflix catalog
Here we are using and explicit $top of 1 meaning skip the first record and then return the next 5 records which are titles 1-6 in the catalog.
How do I get the number of records in the set?
Obtaining the number of records in a set is normally done one of two ways depending on the context.
The $count service request returns the number of records in a collection or if the collection has a filter, the number of records matching the filter.
For example to get a count of the number of titles that netflix has stored you would use:
As at writing this is reporting as 160050
The other option is to use the $inlinecount directive to get the count as part of the response body. Let us say for example you would like to read the 5 records but would also like to know how many records there are in total so that the paging controls and record count label can for example be updated then the count will be returned in the count element in the metadata namespace.
<feed …. xmlns:m=”http://schemas.microsoft.com/ado/2007/08/dataservices/metadata” …>
or in JSON
For example to get a count of the number of titles Netflix has available as well as the first 5 records, you will make the request
This will return the same number of records as $count in the count element or property but only the first 5 entities will be returned as requested by the $top system query option. This is very useful in the mobile scenario where pagination is typically used to improve performance. For example we can take the count and divide it by the number of items we want on a page and this will yield the number of pages in the recordset and then this makes it easy to calculate the $top and $skip values to navigate between pages or navigate to an arbitrary page.
In the next post we will look at the $select and $expand system query options to restrict the amount of data and/or reduce the number of round trips to the server.